<?php

namespace App\Models;

use App\Http\Controllers\Pc\TimingController;
use App\Libs\wrapper\Task;
use App\Models\Datawhole;
use App\Models\ResourceModel\AmazonBuhuoRequestModel;
use App\Models\ResourceModel\TransportationMode;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Jobs\AmazonSalesController;
use Illuminate\Support\Facades\Redis;
use Mockery\Exception;
use Symfony\Component\VarDumper\VarDumper;
use Carbon\Carbon;
use App\Models\ResourceModel\AmazonBoxDataModel;
use App\Models\ResourceModel\AmazonCreateGoodsModel;
use App\Models\ResourceModel\CustomSkuModel;
use App\Models\ResourceModel\GroupCustomSkuModel;
use App\Models\ResourceModel\AmazonBuhuoDetailModel;
use App\Models\ResourceModel\SkuModel;
use PDO;

class DigitalModel extends BaseModel
{
    // 国家标识
    const NATIONAL_IDENTITY = [
        'NA' => 'US',
        'FE' => 'JP',
        'EU' => 'EU'
    ];
    const NATIONAL_IDENTITY_NAME = [
        'US' => '美国',
        'JP' => '日本',
        'EU' => '欧洲'
    ];
    // 运输类型
    const TRANSPORTATION_TYPE = [
        '1' => '海运',
        '2' => '快递',
        '3' => '空运',
        '4' => '铁路',
        '5' => '卡航'
    ];
    protected $replenishmentModel;
    protected $replenishmentDetailModel;
    protected $createGoodsModel;
    protected $boxDataModel;
    protected $customSkuModel;
    protected $groupCustomSkuModel;
    protected $skuModel;
    protected $transportationModeModel;
    protected $amazonBuhuoReqeustModel;
    protected $amazonBuhuoDetailModel;

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->replenishmentModel = new AmazonBuhuoRequestModel();
        $this->replenishmentDetailModel = new AmazonBuhuoDetailModel();
        $this->createGoodsModel = new AmazonCreateGoodsModel();
        $this->boxDataModel = new AmazonBoxDataModel();
        $this->customSkuModel = new CustomSkuModel();
        $this->groupCustomSkuModel = new GroupCustomSkuModel();
        $this->skuModel = new SkuModel();
        $this->transportationModeModel = new TransportationMode();
        $this->amazonBuhuoReqeustModel = new AmazonBuhuoRequestModel();
        $this->amazonBuhuoDetailModel = new AmazonBuhuoDetailModel();
    }


    //工厂直发仓补货
    public function getFactoryBuhuo($params){
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页 
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $list = db::table('self_sku as a')
        ->leftjoin('self_custom_sku as b','a.custom_sku_id','=','b.id')
        ->leftjoin('cloudhouse_custom_sku as c','b.id','=','c.custom_sku_id')
        ->leftjoin('cloudhouse_contract_total as d','c.contract_no','=','d.contract_no')
        ->leftjoin('self_spu as e','a.spu_id','=','e.id')
        ->where('c.order_id','>',0)
        ->where('c.num','>',0);


        if(isset($params['shop_id'])){
            $list = $list->where('a.shop_id',$params['shop_id']);
        }
        if(isset($params['user_id'])){
            $list = $list->where('a.user_id',$params['user_id']);
        }
        if(isset($params['sku'])){
            $list = $list->where(function ($query) use($params){
                $query->where('a.sku','like','%'.$params['sku'].'%')->orWhere('a.old_sku','like','%'.$params['sku'].'%');
            });
        }
        if(isset($params['custom_sku'])){
            $list = $list->where(function ($query) use($params){
                $query->where('b.custom_sku','like','%'.$params['custom_sku'].'%')->orWhere('b.old_custom_sku','like','%'.$params['custom_sku'].'%');
            });
        }
        if(isset($params['spu'])){
            $list = $list->where(function ($query) use($params){
                $query->where('e.spu','like','%'.$params['spu'].'%')->orWhere('e.old_spu','like','%'.$params['spu'].'%');
            });
        }

        if(isset($params['sku_ids'])){
            $list = $list->whereIn('a.id',$params['sku_ids']);
        }

        if(isset($params['request_num'])){
            $request_num = $params['request_num'];
        }
        

        $list = $list
        ->where('d.contract_status',2)
        ->groupby('a.id')
        // ->select('a.id','a.sku','a.shop_id','b.id as custom_sku_id','b.custom_sku','c.num','d.supplier_id','d.contract_no','c.order_id');
        ->select('a.id as sku_id','a.user_id','a.spu','a.spu_id','a.sku','a.old_sku','a.shop_id','b.id as custom_sku_id','b.custom_sku','e.one_cate_id','e.three_cate_id',db::raw('sum(c.num) as total'),db::raw('group_concat(d.supplier_id) as supplier_ids'),db::raw('group_concat(d.contract_no) as contract_nos'),db::raw('group_concat(c.order_id) as order_ids'));


        $totalNum = $list->get()->count();


        $list = $list->offset($pagenNum)
        ->limit($limit)
        ->get();

        $sku_ids = array_column($list->toarray(),'sku_id');


        //获取fba库存  fnsku
        $product = db::table('product_detail')->whereIn('sku_id',$sku_ids)->get();

        $product_res = [];
        foreach ($product as $pv) {
            # code...
            $product_res[$pv->sku_id]['fnsku'] = $pv->fnsku;
            $product_res[$pv->sku_id]['in_stock_num'] = $pv->in_stock_num;
            $product_res[$pv->sku_id]['in_bound_num'] = $pv->in_bound_num;
            $product_res[$pv->sku_id]['transfer_num'] = $pv->transfer_num;

        }


        //获取近一周销量  近2周销量
        $start_time2 = date('Y-m-d 00:00:00',time()-(86400*15));
        $start_time = date('Y-m-d 00:00:00',time()-(86400*7));
        $end_time = date('Y-m-d 23:59:59',time());

        $orders_week = Db::table('amazon_order_item')->where('order_status','!=','Canceled')->whereIn('sku_id',$sku_ids)->whereBetween('amazon_time', [$start_time, $end_time])->select('sku_id','quantity_ordered')->get();

        $orders_week2 = Db::table('amazon_order_item')->where('order_status','!=','Canceled')->whereIn('sku_id',$sku_ids)->whereBetween('amazon_time', [$start_time2, $start_time])->select('sku_id','quantity_ordered')->get();


        $order_week_res = [];
        foreach ($orders_week as $owv) {
            # code...
            $order_week_res[$owv->sku_id] = $owv->quantity_ordered;

        }

        $order_week2_res = [];
        foreach ($orders_week2 as $owv2) {
            # code...
            $order_week2_res[$owv2->sku_id] = $owv2->quantity_ordered;

        }




        foreach ($list as $v) {

            $v->supplier_ids = array_unique(explode(',',$v->supplier_ids));
            $v->contract_nos = implode(',',array_unique(explode(',',$v->contract_nos)));
            //合同总数-已生产计划 = 可用
            $v->dec_num = 0;

            $requrst_res = db::table('amazon_buhuo_detail as a')->leftjoin('amazon_buhuo_request as b','a.request_id','=','b.id')->where('a.custom_sku_id',$v->custom_sku_id)->where('b.request_status','!=',1)->where('b.request_type',2)->whereIn('a.supplier_id',$v->supplier_ids)->select('a.request_num','a.request_id','b.request_userid')->get();

            $request_ids = [];
            $request_idss =[];
            foreach ($requrst_res as $rqv) {
                # code...
                $rqv_o = [];
                $rqv_o['request_id'] = $rqv->request_id;
                $rqv_o['request_num'] = $rqv->request_num;
                $rqv_o['user'] = $this->GetUsers($rqv->request_userid)['account']??'';
                $request_ids[$rqv->request_id] = $rqv_o;
                $v->dec_num+=$rqv->request_num;
                $request_idss[] = $rqv->request_id;

            }
            $v->request_detail = array_values($request_ids);

            $v->request_ids = implode(',',array_unique($request_idss));
            $v->num = $v->total- $v->dec_num;

            if(isset($request_num[$v->sku_id])){
                $v->request_num = $request_num[$v->sku_id];
            }

            $v->fnsku = '';
            $v->in_stock_num = 0;
            $v->in_bound_num = 0;
            $v->transfer_num = 0;

            if(isset($product_res[$v->sku_id])){
                $v->fnsku = $product_res[$v->sku_id]['fnsku'];
                $v->in_stock_num = $product_res[$v->sku_id]['in_stock_num'];
                $v->in_bound_num = $product_res[$v->sku_id]['in_bound_num'];
                $v->transfer_num = $product_res[$v->sku_id]['transfer_num'];
            }

            $v->tweek_order_num = 0;
            $v->week_order_num = 0;
            $v->day_order_num = 0;
            $v->tday_order_num = 0;
            if(isset($order_week_res[$v->sku_id])){
                $v->week_order_num = $order_week_res[$v->sku_id];
                if($v->week_order_num>0){
                    $v->day_order_num = round($v->week_order_num/7,2);
                }

            }
            if(isset($order_week2_res[$v->sku_id])){
                $v->tweek_order_num = $order_week2_res[$v->sku_id]+$v->week_order_num;
                if($v->tweek_order_num>0){
                    $v->tday_order_num = round($v->tweek_order_num/14,2);
                }
 
            }

            $v->fba_inventory_day = 999;

            $v->fba_inventory = $v->in_stock_num+$v->in_bound_num+$v->transfer_num;
            if($v->fba_inventory>0 && $v->day_order_num>0){
                $v->fba_inventory_day = ceil($v->fba_inventory/$v->day_order_num);
            }

            $v->img = $this->GetCustomskuImg($v->custom_sku);

            $v->user = $this->GetUsers($v->user_id)['account'];

            $v->shop_name = $this->GetShop($v->shop_id)['shop_name'];

            $v->one_cate = $this->GetCategory($v->one_cate_id)['name'];
            $v->three_cate = $this->GetCategory($v->three_cate_id)['name'];
            # code...
            $v->detail = $this->getFactoryBuhuoNum($v->custom_sku_id);
        }

        return [
            'type' =>'success',
            'data' => $list,
            'totalnum' => $totalNum,
        ];

    }



    //查看直发仓库存明细
    public function getFactoryBuhuoNum($custom_sku_id){
        $list = db::table('cloudhouse_custom_sku as c')
        ->leftjoin('cloudhouse_contract_total as d','c.contract_no','=','d.contract_no')
        ->where('c.order_id','>',0)
        ->where('d.contract_status',2)
        ->where('c.custom_sku_id',$custom_sku_id)
        ->groupby('d.supplier_id')
        ->select('c.custom_sku_id',db::raw('sum(c.num) as total'),'d.supplier_id',db::raw('group_concat(d.contract_no) as contract_nos'),db::raw('group_concat(c.order_id) as order_ids'))
        // ->select('a.id','a.sku','a.shop_id','b.id as custom_sku_id','b.custom_sku','c.num','d.supplier_id','d.contract_no','c.order_id');
        // ->select('a.id as sku_id','a.user_id','a.spu','a.spu_id','a.sku','a.shop_id','a.custom_sku_id','a.custom_sku','c.num','d.supplier_id','d.contract_no','c.order_id')
        ->get();


        $return = [];
        foreach ($list as $v) {
            $v->supplier_name = '';
            $supplier = db::table('suppliers')->where('Id',$v->supplier_id)->first();
            if($supplier){
                $v->supplier_name = $supplier->supplier_no;
            }

            $v->dec_num = db::table('amazon_buhuo_detail as a')->leftjoin('amazon_buhuo_request as b','a.request_id','=','b.id')->where('a.custom_sku_id',$v->custom_sku_id)->where('a.supplier_id',$v->supplier_id)->where('b.request_type',2)->where('b.request_status','!=',1)->sum('request_num')??0;

            // $v->dec_num = db::table('amazon_buhuo_report_num')->where('custom_sku_id',$v->custom_sku_id)->where('supplier_id',$v->supplier_id)->sum('num')??0;

            $v->num = $v->total - $v->dec_num;

            $rd['supplier_name'] = $v->supplier_name;
            $rd['supplier_id'] = $v->supplier_id;
            $rd['contract_nos'] = $v->contract_nos;
            $rd['order_ids'] = $v->order_ids;
            $rd['total'] = $v->total;
            $rd['dec_num'] = $v->dec_num;
            $rd['num'] = $v->num;

            $return[] = $rd;
            # code...
        }
        return $list;
    }

    //补货预警报表
    public function getBuhuoWarnNew($params)
    {
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页 111
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $list = Db::table('cache_buhuo_warning as a')
            ->leftjoin('self_sku as b','a.sku_id','=','b.id')
            ->leftjoin('self_custom_sku as c','b.custom_sku_id','=','c.id')
            ->leftjoin('self_spu as d','c.spu_id','=','d.id')
            ->leftjoin('self_base_spu as e','d.base_spu_id','=','e.id');
        if(isset($params['buhuo_satus'])){
            $list =  $list ->whereIn('a.buhuo_satus',$params['buhuo_satus']);
        }
        if(isset($params['sale_status'])){
            $list =  $list ->where('b.sales_status',$params['sale_status']);
        }
        if(isset($params['user_id'])){
            $list =  $list ->where('b.user_id',$params['user_id']);
        }
        if(isset($params['one_cate_id'])){
            $list =  $list ->where('e.one_cate_id',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $list =  $list ->where('e.two_cate_id',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $list =  $list ->where('e.three_cate_id',$params['three_cate_id']);
        }
        if(isset($params['shop_id'])){
            $list =  $list ->where('b.shop_id',$params['shop_id']);
        }
        if(isset($params['sku_id'])){
            $list =  $list ->whereIn('b.id',$params['sku_id']);
        }
        if(isset($params['asin'])){
            $asin = explode(',', trim($params['asin']));
            $list =  $list ->whereIn('b.asin', $asin);
        }
        if(isset($params['fasin'])){
            $fasin = explode(',', trim($params['fasin']));
            $list =  $list ->whereIn('b.fasin', $fasin);
        }
        if (isset($params['sku'])) {
            $sku = explode(',', trim($params['sku']));
            $list =  $list->where(function ($query) use ($sku){
                foreach ($sku as $item) {
                    $query->orWhere('b.sku', 'like', '%' . $item . '%')
                        ->orWhere('b.old_sku', 'like', '%' . $item . '%');
                }
            });
        }
        if (isset($params['custom_sku'])) {
            $custom_sku = explode(',', trim($params['custom_sku']));
            $list =  $list->where(function ($query) use ($custom_sku){
                foreach ($custom_sku as $item) {
                    $query->orWhere('c.custom_sku', 'like', '%' . $item . '%')
                        ->orWhere('c.old_custom_sku', 'like', '%' . $item . '%');
                }
            });
        }
        if (isset($params['spu'])) {
            $spu = explode(',', trim($params['spu']));
            $list =  $list->where(function ($query) use ($spu){
                foreach ($spu as $item) {
                    $query->orWhere('b.sku', 'like', '%' . $item . '%')
                        ->orWhere('b.old_sku', 'like', '%' . $item . '%');
                }
            });
        }

        $totalNum = $list->count();

        $order = 'tweek_order_num';
        if (isset($params['order'])){
            $order = $params['order'];
        }

    //    DB::connection()->enableQueryLog();
        if(isset($params['sku_id'])){
            $list = $list
                ->offset($pagenNum)
                ->limit($limit)
                //新仓储管理取值
                ->select('a.*','c.deposit_inventory as deposit_num','b.sku','b.plan_multiple','b.shop_id','b.id as sku_id','c.id as custom_sku_id','d.id as spu_id','b.old_sku','b.user_id','b.fasin','c.custom_sku','c.old_custom_sku','c.cloud_num', 'c.type as custom_sku_type', 'd.spu','d.old_spu','d.type as sputype','d.sales_status','e.one_cate_id','e.three_cate_id','c.deposit_inventory','c.direct_inventory')
//                ->select('a.*','c.deposit_inventory','b.sku','b.plan_multiple','b.shop_id','f.fnsku','b.id as sku_id','c.id as custom_sku_id','d.id as spu_id','b.old_sku','b.user_id','b.fasin','c.custom_sku','c.old_custom_sku','c.cloud_num','c.factory_num', 'c.type as custom_sku_type', 'd.spu','d.old_spu','d.type as sputype','d.sales_status','e.one_cate_id','e.three_cate_id')
                ->orderby(DB::raw("FIND_IN_SET(b.id, '" . implode(',', $params['sku_id']) . "'" . ')'))
                ->get();
        }else{
            $list = $list
                ->offset($pagenNum)
                ->limit($limit)
                //新仓储管理取值
               ->select('a.*','c.deposit_inventory as deposit_num','b.sku','b.plan_multiple','b.shop_id','b.id as sku_id','c.id as custom_sku_id','d.id as spu_id','b.old_sku','b.user_id','b.fasin','c.custom_sku','c.old_custom_sku','c.cloud_num', 'c.type as custom_sku_type', 'd.spu','d.old_spu','d.type as sputype','d.sales_status','e.one_cate_id','e.three_cate_id','c.deposit_inventory','c.direct_inventory')
                ->orderby('a.'.$order,'DESC')
                ->get();
        }

    //     print_r(DB::getQueryLog());
    //    var_dump($list);


        $lists = json_decode(json_encode($list),true);
        $custom_sku_ids = array_column($lists,'custom_sku_id');
        $sku_ids = array_column($lists,'sku_id');

        //获取锁定库存
        $requestres = $this->lock_inventory($custom_sku_ids,[5]);

        // 获取所有无创货件数据的补货申请详情
        $requestMdl = $this->amazonBuhuoReqeustModel::query()
            ->leftJoin('amazon_create_goods as a', 'a.request_id', '=', 'amazon_buhuo_request.id')
            ->where('amazon_buhuo_request.request_status', '>=', 0)
            ->whereNull('a.id')
            ->get(['amazon_buhuo_request.id']);
        $requestIds = [];
        if ($requestMdl->isNotEmpty()){
            $requestIds = array_column($requestMdl->toArray(), 'id');
        }
        $requestDetailList = $this->amazonBuhuoDetailModel::query()
            ->whereIn('request_id', $requestIds)
            ->get();

        $update_time = '';
        $zuheData = [];


        //获取平台的库位库存
        $cloudhouse_num = DB::table('cloudhouse_location_num as a')
        ->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
        ->where('a.platform_id',5)
        ->whereIn('a.custom_sku_id',$custom_sku_ids )
        ->select('a.num','b.warehouse_id','a.custom_sku_id')
        ->get();

        $t_l_iven = [];
        $q_l_iven = [];
        $c_l_iven = [];
        $f_l_iven = [];
        $z_l_iven = [];



        //获取fnsku
        $product_detail = db::table('product_detail')->whereIn('sku_id',$sku_ids)->get();
        $product_arr = [];
        foreach ($product_detail as $pv) {
            # code...
            $product_arr[$pv->sku_id] = $pv->fnsku;
        }
        foreach ($cloudhouse_num as $v) {
            # code...
            if($v->warehouse_id==1){
                //同安仓
                if(isset($t_l_iven[$v->custom_sku_id])){
                    $t_l_iven[$v->custom_sku_id]+=$v->num;
                }else{
                    $t_l_iven[$v->custom_sku_id]=$v->num;
                }
            }elseif($v->warehouse_id==2){
                //泉州仓
                if(isset($q_l_iven[$v->custom_sku_id])){
                    $q_l_iven[$v->custom_sku_id]+=$v->num;
                }else{
                    $q_l_iven[$v->custom_sku_id]=$v->num;
                }
            }elseif($v->warehouse_id==3){
                //云仓
                if(isset($c_l_iven[$v->custom_sku_id])){
                    $c_l_iven[$v->custom_sku_id]+=$v->num;
                }else{
                    $c_l_iven[$v->custom_sku_id]=$v->num;
                }
            }elseif($v->warehouse_id==6){
                //工厂寄存仓
                if(isset($f_l_iven[$v->custom_sku_id])){
                    $f_l_iven[$v->custom_sku_id]+=$v->num;
                }else{
                    $f_l_iven[$v->custom_sku_id]=$v->num;
                }
            }elseif($v->warehouse_id==21){
                //工厂直发仓
                if(isset($z_l_iven[$v->custom_sku_id])){
                    $z_l_iven[$v->custom_sku_id]+=$v->num;
                }else{
                    $z_l_iven[$v->custom_sku_id]=$v->num;
                }
            }

        }

        //查询已开合同数据
        $cloudhouse_custom_sku = Db::table('cloudhouse_custom_sku as a')
            ->leftJoin('cloudhouse_contract_total as b','a.contract_no','=','b.contract_no')
            ->whereIn('a.custom_sku_id',$custom_sku_ids)
            ->where('a.contract_no','!=','')
            ->where('b.is_end',0)
            ->select('a.custom_sku_id','a.num','a.contract_no')
            ->get()->toArray();
        $contractNum = [];
        $contractArr = [];
        foreach ($cloudhouse_custom_sku as $b){
            if(isset($contractNum[$b->custom_sku_id])){
                $contractNum[$b->custom_sku_id] += $b->num;
            }else{
                $contractNum[$b->custom_sku_id] = $b->num;
            }
            $contractArr[] = $b->contract_no;
        }
        $contractArr = array_unique($contractArr);

        //查询合同已出数据
        $goods_transfers = Db::table('goods_transfers as a')
            ->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')
            ->whereIn('b.contract_no',$contractArr)
            ->whereIn('b.custom_sku_id',$custom_sku_ids)
            ->where('a.is_push','>',0)
            ->where('a.type',1)
            ->select('a.type_detail','b.receive_num','b.custom_sku_id')
            ->get()->toArray();

        foreach ($goods_transfers as $g){
            if(isset($contractNum[$g->custom_sku_id])){
                if($g->type_detail==2){
                    $contractNum[$g->custom_sku_id] -= $g->receive_num;
                }
                if($g->type_detail==9){
                    $contractNum[$g->custom_sku_id] += $g->receive_num;
                }
            }
        }

        foreach ($list as $v) {
            //工厂虚拟仓库存
            if(isset($contractNum[$v->custom_sku_id])){
                $v->factory_num = $contractNum[$v->custom_sku_id]>0?$contractNum[$v->custom_sku_id]:0;
            }else{
                $v->factory_num = 0;
            }
            $v->fnsku = '';
            if(isset($product_arr[$v->sku_id])){
                $v->fnsku =$product_arr[$v->sku_id];
            }
            if(empty($update_time)){
                $update_time = $v->update_time;
            }
            if($v->old_sku){
                $v->sku = $v->old_sku;
            }
            if($v->old_custom_sku){
                $v->custom_sku = $v->old_custom_sku;
            }


            // 未提供箱唛数量
            $v->not_shipping_mark_num = 0;
            foreach ($requestDetailList as $detail){
                if ($v->custom_sku_id == $detail->custom_sku_id){
                    // edit:2023-04-06 运输方式及数量变动
                    $v->not_shipping_mark_num = $detail->request_num;
                }
            }

            $v->user  = '';
            $user = $this->GetUsers($v->user_id);
            if($user){
                $v->user = $user['account'];
            }
            //大类
            $v->one_cate = '';
            $one_cate = $this->GetCategory($v->one_cate_id);
            if($one_cate){
                $v->one_cate = $one_cate['name'];
            }

            //三类
            $v->three_cate = '';
            $three_cate = $this->GetCategory($v->three_cate_id);
            if($three_cate){
                $v->three_cate = $three_cate['name'];
            }

            $shop = $this->GetShop($v->shop_id);
            if($shop){
                $v->shop_name = $shop['shop_name'];
            }else{
                $v->shop_name = '';
            }

//            $v->tongan_num  = 0;
//            $v->quanzhou_num = 0;
            $v->tongan_request_num = 0;
            $v->quanzhou_request_num = 0;
            $v->cloud_request_num = 0;
            $v->deposit_request_num = 0;
            $v->direct_request_num = 0;


            $v->courier =  $v->courier_num;
            $v->shipping = $v->shipping_num;
            $v->air = $v->air_num;
//            $v->railway = $v->railway_num;
//            $v->cardair = $v->cardair_num;

            $v->courier_num = 0;
            $v->shipping_num = 0;
            $v->air_num = 0;
//            $v->railway_num = 0;
//            $v->cardair = 0;


            if(isset($requestres[$v->custom_sku_id][1])){
                $v->tongan_request_num = $requestres[$v->custom_sku_id][1];
            }
            if(isset($requestres[$v->custom_sku_id][2])){
                $v->quanzhou_request_num = $requestres[$v->custom_sku_id][2];
            }
            if(isset($requestres[$v->custom_sku_id][3])){
                $v->cloud_request_num = $requestres[$v->custom_sku_id][3];
            }
            if(isset($requestres[$v->custom_sku_id][6])){
                $v->deposit_request_num = $requestres[$v->custom_sku_id][6];
            }
            if(isset($requestres[$v->custom_sku_id][21])){
                $v->direct_request_num = $requestres[$v->custom_sku_id][21];
            }


            $v->tongan_num = 0;
            $v->quanzhou_num = 0;
            $v->cloud_num = 0;
            $v->quanzhou_num = 0;
            $v->direct_num = 0;

            if(isset($t_l_iven[$v->custom_sku_id])){
                $v->tongan_num =$t_l_iven[$v->custom_sku_id];
            }
            if(isset($q_l_iven[$v->custom_sku_id])){
                $v->quanzhou_num = $q_l_iven[$v->custom_sku_id];
            }
            if(isset($c_l_iven[$v->custom_sku_id])){
                $v->cloud_num = $c_l_iven[$v->custom_sku_id];
            }
            if(isset($f_l_iven[$v->custom_sku_id])){
                $v->deposit_num = $f_l_iven[$v->custom_sku_id];
            }
            if(isset($z_l_iven[$v->custom_sku_id])){
                $v->direct_num = $z_l_iven[$v->custom_sku_id];
            }


            $v->tongan_deduct_request_num = 0;
            $v->quanzhou_deduct_request_num = 0;
            $v->cloud_deduct_request_num = 0;
            $v->deposit_deduct_request_num = 0;
            $v->direct_deduct_request_num = 0;


            //预减=本地仓-计划
            $v->tongan_deduct_request_num = $v->tongan_num - $v->tongan_request_num;
            $v->quanzhou_deduct_request_num = $v->quanzhou_num - $v->quanzhou_request_num;
            $v->cloud_deduct_request_num = $v->cloud_num - $v->cloud_request_num;
            $v->deposit_deduct_request_num = $v->deposit_num - $v->deposit_request_num;
            $v->direct_deduct_request_num = $v->direct_num - $v->direct_deduct_request_num;


            $v->shipment_order_num = $v->tongan_request_num +$v->quanzhou_request_num +$v->cloud_request_num + $v->deposit_deduct_request_num + $v->direct_deduct_request_num;

            //总预减
//
            $v->deduct_total = $v->tongan_deduct_request_num+$v->quanzhou_deduct_request_num+$v->cloud_deduct_request_num+$v->deposit_deduct_request_num + $v->direct_deduct_request_num;


            $v->img = $this->GetCustomskuImg($v->custom_sku);

            $v->fba_total = $v->in_stock_num + $v->transfer_num + $v->in_bound_num;

            if($v->buhuo_satus==1){
                $v->buhuo_status = '需要补货';
            }elseif($v->buhuo_satus==2){
                $v->buhuo_status = '库存偏多';
            }elseif($v->buhuo_satus==3){
                $v->buhuo_status = '库存冗余';
            }else{
                $v->buhuo_status = '';
            }
           
            $v->tweek_roder_num = $v->tweek_order_num;

            $v->inventory_total = $v->tongan_num + $v->quanzhou_num + $v->cloud_num + $v->factory_num+$v->fba_total +$v->deposit_num;


        }

        $posttype = $params['posttype']??1;

        if($posttype==2){
            $p['title']='补货预警表'.time();
            $p['title_list']  = [
                'sku'=>'sku',
                'custom_sku'=>'库存sku',
                'spu'=>'spu',
                'user'=>'运营',
                'shop_name'=>'店铺',
                'in_stock_num'=>'fba在仓库存',
                'transfer_num'=>'fba预留库存',
                'in_bound_num'=>'fba在途库存',
                'week_order_num'=>'周销',
                'day_order_num'=>'周日销',
                'tweek_roder_num'=>'两周销',
                'tday_order_num'=>'两周日销',
                'buhuo_status'=>'补货状态',
                'fba_inventory_day'=>'fba周转天数',
                'total_need_inventory'=>'建议补货数量',
                'factory_num'=>'工厂虚拟仓',
                'deposit_num'=>'工厂寄存仓',
                'deposit_deduct_request_num'=>'工厂寄存仓预减',
                'cloud_num'=>'云仓',
                'cloud_deduct_request_num'=>'云仓预减',
                'tongan_num'=>'同安仓',
                'tongan_deduct_request_num'=>'同安仓预减',
                'quanzhou_num'=>'泉州仓',
                'quanzhou_deduct_request_num'=>'泉州仓预减',
                'shipment_order_num'=>'总下单',
                'inventory_total'=>'总库存',
                'courier'=>'建议快递',
                'shipping'=>'建议海运',
                'air'=>'建议空运',
            ];

           
            $p['data'] =   $list;
            $find_user_id = $params['find_user_id']??1;
            $p['user_id'] = $find_user_id;
            $p['type'] = '补货预警表-导出';
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }

        return [
            'type' =>'success',
            'data' => $list,
            'totalnum' => $totalNum,
            'last_update_time'=> $update_time,
            'zuhe_data'=> $zuheData,
            'requestres'=>$requestres,
        ];


    }


    //获取下单id
    public function getOrderListByCus($params){
        $custom_sku_id = $params['custom_sku_id'];
        $user_id = $params['user_id'];
        $list = db::table('amazon_place_order_task as a')->leftjoin('cloudhouse_custom_sku as b','a.id','=','b.order_id')->whereIn('b.custom_sku_id',$custom_sku_id)->where('a.user_id',$user_id)->select('a.id','b.custom_sku_id')->get()->toArray();

        $data = [];
        foreach ($list as $v) {
            # code...
            $data[$v->custom_sku_id][] = $v->id;
        }
        return ['type'=>'success','data'=>$data];
    }


    //获取合同下单数
    public function getCusNumByContract($params){
        $user_id = $params['user_id']??0;
        $order_id = $params['order_id']??0;
        $custom_sku_id = $params['custom_sku_id']??0;

        if($order_id==0||$custom_sku_id==0||$user_id==0){
            $data['total'] = 0;
            $data['num'] = 0;
            $data['wait_outnum'] = 0;
            return ['type'=>'success','data'=>$data];
        }

        $amazon_place_order_task = db::table('amazon_place_order_task')->where('id',$order_id)->first();
        if($amazon_place_order_task->user_id!=$user_id){
            return ['type'=>'fail','msg'=>'非下单人，下单人为'.$this->GetUsers($amazon_place_order_task->user_id)['account']??''];
        }
        // $contract = db::table('cloudhouse_contract_total as a')->leftjoin('cloudhouse_custom_sku as b','a.contract_no','=','b.contract_no')->where('b.order_id',$order_id)->where('b.custom_sku_id',$custom_sku_id)->where('a.contract_status',2)->select('a.supplier_id','a.contract_no','b.num')->get();
        $contract = db::table('cloudhouse_contract_total as a')->leftjoin('cloudhouse_custom_sku as b','a.contract_no','=','b.contract_no')->where('b.order_id',$order_id)->where('b.custom_sku_id',$custom_sku_id)->select('a.supplier_id','a.contract_no','b.num')->get();
        // var_dump($contract);
        // return;
        if(!$contract->isNotEmpty()){
            return ['type'=>'fail','msg'=>'无此下单数据'];
        }
        $total = 0;
        $num = 0;
        $supplier_id = 0;
        $wait_outnum = 0;
        if($contract){
            foreach ($contract as $v) {
                # code...
                $total+=$v->num;
                $supplier_id = $v->supplier_id;
                $contract_no = $v->contract_no;
            }

            $goods_transfers_detail = db::table('goods_transfers_detail as a')->leftjoin('goods_transfers as b','a.order_no','=','b.order_no')->where('b.contract_no','like','%'.$contract_no.'%')->whereIn('b.is_push',[1,2,3,4])->where('a.custom_sku_id',$custom_sku_id)->get();

            

            // 已出货待入库数量 transfers_num-receive_num


            foreach ($goods_transfers_detail as $g_v) {
                $wait_outnum +=$g_v->transfers_num-$g_v->receive_num;
            }

            $out_num = db::table('amazon_buhuo_report_num')->where('order_id',$order_id)->where('custom_sku_id',$custom_sku_id)->sum('num');
            $total = $total-$out_num;
            $box = db::table('self_custom_sku_box')->where('suppliers_id',$supplier_id)->where('custom_sku_id',$custom_sku_id)->first();
            if($box){
                $num = $box->num;
            }
        }



        $data['total'] = $total;
        $data['num'] = $num;
        $data['wait_outnum'] = $wait_outnum;
        return ['type'=>'success','data'=>$data];
    }

    //历史库存报表库存
    public function getHisCusInventory($params)
    {
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页 111
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $res = db::table('self_custom_sku as a')->leftjoin('cache_cus_his as b','a.id','=','b.custom_sku_id')->leftjoin('self_spu as c','a.spu_id','=','c.id');
        if (isset($params['custom_sku'])) {
            $custom_sku = explode(',', trim($params['custom_sku']));
            $res =  $res->where(function ($query) use ($custom_sku){
                foreach ($custom_sku as $item) {
                    $query->orWhere('a.custom_sku', 'like', '%' . $item . '%')
                        ->orWhere('a.old_custom_sku', 'like', '%' . $item . '%');
                }
            });
        }

        if (isset($params['spu'])) {
            $custom_sku = explode(',', trim($params['spu']));
            $res =  $res->where(function ($query) use ($custom_sku){
                foreach ($custom_sku as $item) {
                    $query->orWhere('c.spu', 'like', '%' . $item . '%')
                        ->orWhere('c.old_spu', 'like', '%' . $item . '%');
                }
            });
        }

        if(isset($params['start_time'])){
            $time = $params['start_time'];
            $time = date("Y-m", strtotime("+1 months", strtotime($time)));
            $res = $res->where('ds','like', '%' . $time . '%');
        }
        $totalNum = $res->count();

        $list = $res
        ->offset($pagenNum)
        ->limit($limit)
        ->select('a.custom_sku','a.old_custom_sku','b.*','c.spu','c.old_spu')
        ->get();

        foreach ($list as $v) {
            # code...
            if(!empty($v->old_custom_sku)){
                $v->custom_sku = $v->old_custom_sku;
            }
            if(!empty($v->old_spu)){
                $v->spu = $v->old_spu;
            }
            $v->time = date('Y-m',strtotime($v->ds)-160000);
        }
        return['totalnum'=>$totalNum,'data'=>$list,'type'=>'success'];
    }    


    //历史库存报表渠道
    public function getHisSkuInventory($params)
    {
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页 111
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $res = db::table('self_sku as a')->leftjoin('cache_sku_his as b','a.id','=','b.sku_id')->leftjoin('self_custom_sku as c','a.custom_sku_id','=','c.id')->leftjoin('cache_cus_his as d','c.id','=','d.custom_sku_id')->leftjoin('self_spu as e','a.spu_id','=','e.id');
        if (isset($params['custom_sku'])) {
            $custom_sku = explode(',', trim($params['custom_sku']));
            $res =  $res->where(function ($query) use ($custom_sku){
                foreach ($custom_sku as $item) {
                    $query->orWhere('c.custom_sku', 'like', '%' . $item . '%')
                        ->orWhere('c.old_custom_sku', 'like', '%' . $item . '%');
                }
            });
        }

        if (isset($params['sku'])) {
            $custom_sku = explode(',', trim($params['sku']));
            $res =  $res->where(function ($query) use ($custom_sku){
                foreach ($custom_sku as $item) {
                    $query->orWhere('a.sku', 'like', '%' . $item . '%')
                        ->orWhere('a.old_sku', 'like', '%' . $item . '%');
                }
            });
        }

        if (isset($params['spu'])) {
            $custom_sku = explode(',', trim($params['spu']));
            $res =  $res->where(function ($query) use ($custom_sku){
                foreach ($custom_sku as $item) {
                    $query->orWhere('e.spu', 'like', '%' . $item . '%')
                        ->orWhere('e.old_spu', 'like', '%' . $item . '%');
                }
            });
        }

        if(isset($params['start_time'])){
            $time = $params['start_time'];
            $time = date("Y-m", strtotime("+1 months", strtotime($time)));
            $res = $res->where('ds','like', '%' . $time . '%');
        }
        $totalNum = $res->count();

        $list = $res
        ->offset($pagenNum)
        ->limit($limit)
        ->select('a.sku','a.old_sku','b.*','c.custom_sku','c.old_custom_sku','d.quanzhou_num','d.tongan_num','d.cloud_num','d.factory_num','e.spu','e.old_spu')
        ->get();

        foreach ($list as $v) {
            # code...
            if(!empty($v->old_sku)){
                $v->sku = $v->old_sku;
            }
            if(!empty($v->old_custom_sku)){
                $v->custom_sku = $v->old_custom_sku;
            }
            if(!empty($v->old_spu)){
                $v->spu = $v->old_spu;
            }
            $v->time = date('Y-m',strtotime($v->ds)-160000);
        }
        return['totalnum'=>$totalNum,'data'=>$list,'type'=>'success'];
    }    




      //计划
    public function getRequestByCus($ids){
        $res = Db::table('amazon_buhuo_detail as a')->leftjoin('amazon_buhuo_request as b','a.request_id','=','b.id')->whereIn('b.request_status',[3,4,5,6,7])->whereIn('a.custom_sku_id',$ids)->select('a.request_num','b.warehouse','a.custom_sku_id','a.spu_id')->get();

        $return = [];
        foreach ($res as $v) {
            # code...
            $total = $v->request_num;
            if($v->warehouse==1){
                if(isset($return[$v->custom_sku_id]['tongan_request_num'])){
                    $return[$v->custom_sku_id]['tongan_request_num'] += $total;
                }else{
                    $return[$v->custom_sku_id]['tongan_request_num'] = $total;
                }
            }
            if($v->warehouse==2){
                if(isset($return[$v->custom_sku_id]['quanzhou_request_num'])){
                    $return[$v->custom_sku_id]['quanzhou_request_num'] += $total;
                }else{
                    $return[$v->custom_sku_id]['quanzhou_request_num'] = $total;
                }
            }
            if($v->warehouse==3){
                if(isset($return[$v->custom_sku_id]['cloud_request_num'])){
                    $return[$v->custom_sku_id]['cloud_request_num'] += $total;
                }else{
                    $return[$v->custom_sku_id]['cloud_request_num'] = $total;
                }
            }
            if(isset($return[$v->custom_sku_id]['request_num'])){
                $return[$v->custom_sku_id]['request_num'] += $v->request_num;
            }else{
                $return[$v->custom_sku_id]['request_num'] = $v->request_num;
            }
        }
        return $return;
    }


    
//    public function getBuhuoWarn($params)
//    {
//
//        $type = isset($params['type']) ? $params['type'] : 1;  //类型  查询1 导出2
//        $pagenum = isset($params['page']) ? $params['page'] : 1;
//        $limit = isset($params['limit']) ? $params['limit'] : 30;
//        $page  =  $pagenum- 1;
//        if($page!=0){
//            $page  =  $page * $limit;
//        }
//        $daySum = isset($params['daySum']) ? $params['daySum'] : 14;//近两周天数
//        $lastDay = isset($params['lastDay']) ? $params['lastDay'] : 30;//近一月天数
//        $month = isset($params['month']) ? $params['month'] : date('m');//月
//        $day = isset($params['day']) ? $params['day'] : date('d');//日
//        $year = date('Y');//年
//        $thisDaySum = 7;//近一周天数
//        //上周
//        $startTime = date('Y-m-d 00:00:00', strtotime('-8 days',strtotime($year.'-'.$month.'-'.$day)));
//        $endTime = date('Y-m-d 00:00:00', strtotime('-1 days',strtotime($year.'-'.$month.'-'.$day)));
//        //上上周
//        $startTimeTwo = date('Y-m-d 00:00:00', strtotime('-15 days',strtotime($year.'-'.$month.'-'.$day)));
//        $endTimeTwo = date('Y-m-d 00:00:00', strtotime('-8 days',strtotime($year.'-'.$month.'-'.$day)));
//        //月
//        $startTimeMonth = date('Y-m-d 00:00:00', strtotime("-{$lastDay} days",strtotime($year.'-'.$month.'-'.$day)));
//        $endTimeMonth = $endTime;
//        //年
//        $startTimeYear = $year.'-01-01 :00:00:00';
//        $endTimeYear = $year.'-12-31 :23:59:59';
//        $thisDaySum = 7;
//
//
//        // DB::connection()->enableQueryLog();
//    // print_r(DB::getQueryLog());
//        // 新cus  旧cus  新spu  旧spu
//
//        // sku  =  cus  spu
//
//
//
//        // $list =  Db::table('self_sku as sk')->leftjoin('self_custom_sku as sc','sk.custom_sku', '=', 'sc.custom_sku')->leftjoin('self_spu as sp','sk.spu','=','sp.spu')->limit(100)->get(['sk.*','sp.old_spu','sp.one_cate_id','sp.two_cate_id','sp.three_cate_id','sc.old_custom_sku','sc.img']);
//
//
//        // $query =  Db::table('self_sku as sk')->leftjoin('self_custom_sku as sc','sk.custom_sku', '=', 'sc.old_custom_sku')->leftjoin('self_spu as sp','sk.spu','=','sp.old_spu')->limit(100)->get(['sk.*','sp.old_spu','sp.one_cate_id','sp.two_cate_id','sp.three_cate_id','sc.old_custom_sku','sc.img'])->union($list);
//
//
//        // // $querySql = $query->toSql();
//        // // $result = DB::table(DB::raw("($querySql) as a"))->mergeBindings($query);
//
//
//        // var_dump($query);
//        // exit;
//
//        // print_r(DB::getQueryLog());
//
//
//
//
//        $list = Db::table('self_sku as sk')->leftjoin('self_custom_sku as sc','sc.id', '=', 'sk.custom_sku_id')->leftjoin('self_spu as sp','sk.spu_id','=','sp.id')->leftjoin('self_color_size as cz','sc.size','=','cz.identifying')->where('sk.status',1);
//        $listcount = Db::table('self_sku as sk')->leftjoin('self_custom_sku as sc','sc.id', '=', 'sk.custom_sku_id')->leftjoin('self_spu as sp','sk.spu_id','=','sp.id')->where('sk.status',1);
//
//
//
//
//        // $list = Db::table('self_sku as sk')
//        //     ->leftjoin('self_custom_sku as sc',function ($join) {
//        //         $join->on('sk.custom_sku', '=', 'sc.custom_sku')->orOn('sk.custom_sku', '=', 'sc.old_custom_sku');
//        //     })
//        //     ->leftjoin('self_spu as sp',function ($join) {
//        //         $join->on('sk.spu','=','sp.spu')->orOn('sk.spu','=','sp.old_spu');
//        //     })
//        //     ->leftjoin('self_color_size as cz','sc.size','=','cz.identifying');
//
//        // $listcount = Db::table('self_sku as sk')
//        //     ->leftjoin('self_custom_sku as sc',function ($join) {
//        //         $join->on('sk.custom_sku', '=', 'sc.custom_sku')->orOn('sk.custom_sku', '=', 'sc.old_custom_sku');
//        //     })
//        //     ->leftjoin('self_spu as sp',function ($join) {
//        //         $join->on('sk.spu','=','sp.spu')->orOn('sk.spu','=','sp.old_spu');
//        //     });
//        // $where['sk.status'] = 1;
//
//        if (!empty($params['store'])) {
//            // $where['sk.shop_id']=$params['store'];
//            $list= $list->where('sk.shop_id',$params['store']);
//            $listcount =$listcount->where('sk.shop_id',$params['store']);
//        }
//
//        if (!empty($params['sale_status'])) {
//            // $where['sk.sale_status'] = $params['sale_status'];
//            $list= $list->where('sk.sale_status',$params['sale_status']);
//            $listcount =$listcount->where('sk.sale_status',$params['sale_status']);
//        }
//
//        //大类
//        if (!empty($params['one_cate_id'])) {
//            // $where['sp.one_cate_id'] = $params['one_cate_id'];
//            $list= $list->where('sp.one_cate_id',$params['one_cate_id']);
//            $listcount =$listcount->where('sp.one_cate_id',$params['one_cate_id']);
//        }
//        //二类
//        if (!empty($params['two_cate_id'])) {
//            // $where['sp.two_cate_id'] = $params['two_cate_id'];
//            $list= $list->where('sp.two_cate_id',$params['two_cate_id']);
//            $listcount =$listcount->where('sp.two_cate_id',$params['two_cate_id']);
//        }
//        //三类
//        if (!empty($params['three_cate_id'])) {
//            // $where['sp.three_cate_id'] = $params['three_cate_id'];
//            $list= $list->where('sp.three_cate_id',$params['three_cate_id']);
//            $listcount =$listcount->where('sp.three_cate_id',$params['three_cate_id']);
//        }
//
//
//        if (!empty($params['user_id'])) {
//            // $where['sk.operate_user_id'] = $params['user_id'];
//            $list= $list->where('sk.user_id',$params['user_id']);
//            $listcount =$listcount->where('sk.user_id',$params['user_id']);
//        }
//
//        if (isset($params['id'])) {
//            $ids = explode(",",$params['id']);
//
//            foreach ($ids as $key => $value) {
//                # code...
//                if($key==0){
//                    $list= $list->where('sk.id',$value);
//                    $listcount =$listcount->where('sk.id',$value);
//                }else{
//                    $list= $list->orwhere('sk.id',$value);
//                    $listcount =$listcount->orwhere('sk.id',$value);
//                }
//            }
//            // $where['sk.id'] = $params['id'];
//
//
//        }
//
//        // if (isset($params['asin'])) {
//        //     $where['pd.asin'] = $params['asin'];
//        // }
//
//        // if (isset($params['father_asin'])) {
//        //     $where['pd.parent_asin'] = $params['father_asin'];
//        // }
//        // DB::connection()->enableQueryLog();
//
//        if (!empty($params['sku'])) {
//            if (strstr($params['sku'], '，')) {
//                $symbol = '，';
//            } elseif (strstr($params['sku'], ',')) {
//                $symbol = ',';
//            } else {
//                $symbol = '';
//            }
//            if ($symbol) {
//                $skuarray = explode($symbol,$params['sku']);
//                foreach ($skuarray as $key => $sku) {
//                    $sku = $this->GetNewSku($sku);
//                    if($key==0){
//                        $list= $list->where(function ($query)  use($sku){
//                            $query->where('sk.sku','like','%'.$sku.'%')->orWhere('sk.old_sku','like','%'.$sku.'%');
//                        });
//                        $listcount =$listcount->where(function ($query)  use($sku){
//                            $query->where('sk.sku','like','%'.$sku.'%')->orWhere('sk.old_sku','like','%'.$sku.'%');
//                        });
//                   }else{
//                        $list= $list->orWhere(function ($query)  use($sku){
//                            $query->where('sk.sku','like','%'.$sku.'%')->orWhere('sk.old_sku','like','%'.$sku.'%');
//                        });
//                        $listcount= $listcount->orWhere(function ($query)  use($sku){
//                            $query->where('sk.sku','like','%'.$sku.'%')->orWhere('sk.old_sku','like','%'.$sku.'%');
//                        });
//                   }
//                }
//            }else {
//                $this_sku = $params['sku'];
//                $list= $list->where(function ($query)  use($this_sku){
//                    $query->where('sk.sku','like','%'.$this_sku.'%')->orWhere('sk.old_sku','like','%'.$this_sku.'%');
//                });
//                $listcount= $listcount->where(function ($query)  use($this_sku){
//                    $query->where('sk.sku','like','%'.$this_sku.'%')->orWhere('sk.old_sku','like','%'.$this_sku.'%');
//                });
//            }
//        }
//        if (!empty($params['custom_sku'])) {
//
//            if (strstr($params['custom_sku'], '，')) {
//                $symbol = '，';
//            } elseif (strstr($params['custom_sku'], ',')) {
//                $symbol = ',';
//            } else {
//                $symbol = '';
//            }
//
//            if ($symbol) {
//                $custom_skuarray = explode($symbol,$params['custom_sku']);
//                foreach ($custom_skuarray as $key => $sku) {
//                    $sku = $this->GetNewCustomSku($sku);
//
//                    if($key==0){
//                        $list= $list->where(function ($query)  use($sku){
//                            $query->where('sc.custom_sku','like','%'.$sku.'%')->orWhere('sc.old_custom_sku','like','%'.$sku.'%');
//                        });
//                        $listcount =$listcount->where(function ($query)  use($sku){
//                            $query->where('sc.custom_sku','like','%'.$sku.'%')->orWhere('sc.old_custom_sku','like','%'.$sku.'%');
//                        });
//                    }else{
//                        $list= $list->orWhere(function ($query)  use($sku){
//                            $query->where('sc.custom_sku','like','%'.$sku.'%')->orWhere('sc.old_custom_sku','like','%'.$sku.'%');
//                        });
//                        $listcount= $listcount->orWhere(function ($query)  use($sku){
//                            $query->where('sc.custom_sku','like','%'.$sku.'%')->orWhere('sc.old_custom_sku','like','%'.$sku.'%');
//                        });
//                    }
//                }
//            }else {
//                $this_sku = $params['custom_sku'];
//                $list= $list->where(function ($query)  use($this_sku){
//                    $query->where('sc.custom_sku','like','%'.$this_sku.'%')->orWhere('sc.old_custom_sku','like','%'.$this_sku.'%');
//                });
//                $listcount= $listcount->where(function ($query)  use($this_sku){
//                    $query->where('sc.custom_sku','like','%'.$this_sku.'%')->orWhere('sc.old_custom_sku','like','%'.$this_sku.'%');
//                });
//            }
//        }
//        if (!empty($params['spu'])) {
//            if (strstr($params['spu'], '，')) {
//                $symbol = '，';
//            } elseif (strstr($params['spu'], ',')) {
//                $symbol = ',';
//            } else {
//                $symbol = '';
//            }
//            if ($symbol) {
//                $spuarray = explode($symbol,$params['spu']);
//                foreach ($spuarray as $key => $spu) {
//                    $spu = $this->GetNewSpu($spu);
//                    if($key==0){
//                        $list= $list->where(function ($query)  use($spu){
//                            $query->where('sp.spu','like','%'.$spu.'%')->orWhere('sp.old_spu','like','%'.$spu.'%');
//                        });
//                        $listcount= $listcount->where(function ($query)  use($spu){
//                            $query->where('sp.spu','like','%'.$spu.'%')->orWhere('sp.old_spu','like','%'.$spu.'%');
//                        });
//                    }else{
//                        $list= $list->orWhere(function ($query)  use($spu){
//                            $query->where('sp.spu','like','%'.$spu.'%')->orWhere('sp.old_spu','like','%'.$spu.'%');
//                        });
//                        $listcount= $listcount->orWhere(function ($query)  use($spu){
//                            $query->where('sp.spu','like','%'.$spu.'%')->orWhere('sp.old_spu','like','%'.$spu.'%');
//                        });
//                    }
//                }
//            } else {
//                $this_spu = $params['spu'];
//                $list= $list->where(function ($query)  use($this_spu){
//                    $query->where('sp.spu','like','%'.$this_spu.'%')->orWhere('sp.old_spu','like','%'.$this_spu.'%');
//                });
//                $listcount= $listcount->where(function ($query)  use($this_spu){
//                    $query->where('sp.spu','like','%'.$this_spu.'%')->orWhere('sp.old_spu','like','%'.$this_spu.'%');
//                });
//            }
//        }
//        if (isset($params['buhuo_type'])) {
//            $buhuo_type = $params['buhuo_type'];
//            if(is_array($buhuo_type)){
//                $list= $list->whereIn('sk.buhuo_status',$buhuo_type);
//                $listcount= $listcount->whereIn('sk.buhuo_status',$buhuo_type);
//            }else{
//                $list= $list->where('sk.buhuo_status',$buhuo_type);
//                $listcount= $listcount->where('sk.buhuo_status',$buhuo_type);
//            }
//        }
//        $list = $list ->offset($page)->limit($limit)->orderby('sc.spu','ASC')->orderby('sc.color','ASC')->orderby('cz.sort','ASC')
//            ->get(['sk.*','sp.old_spu','sp.one_cate_id','sp.two_cate_id','sp.three_cate_id','sc.old_custom_sku','sc.cloud_num','sp.type as sputype','sc.id as custom_sku_id',
//                'sc.factory_num','sc.color','sc.size','sp.id as spu_id','sk.id as sku_id']);
//        // print_r(DB::getQueryLog());
//        $totalNum =  $listcount ->count();
//        //查询销售状态表所有状态数据拼接到$statusName
//        $statusSql = "select `id`,`category_status` from amazon_category_status";
//        $statusData = DB::select($statusSql);
//        $statusName = array();
//        if ($statusData) {
//            foreach ($statusData as $statusVal) {
//                $statusName[$statusVal->id] = $statusVal->category_status;
//            }
//        }
////        var_dump($skuData);die;
//        if (!empty($list)) {
//            //读取父asin，fusku，asin
//            $product_query = array();
////            foreach ($list as $value) {
////                # code...
////                $product_query[] = $value->sku;
////                $product_query[] = $value->old_sku;
////            }
//            $listArr = json_decode(json_encode($list),true);
//            $product_sku = array_column($listArr,'sku');
//            $product_old_sku = array_column($listArr,'old_sku');
//            $product_query = array_merge($product_sku,$product_old_sku);
//
//            $product = DB::table('product_detail')->whereIn('sellersku',$product_query)->get();
//            $productdetail = [];
//            foreach ($product as $pv) {
//                $productdetail[$pv->sellersku] = $pv;
//            }
//            //获取去年销量
//            $lastYear = date('Y') - 1;
//            $lastsaleArr = [];
//            $lastYearData = DB::table('amazon_year_sale')->where('year',$lastYear)->whereIn('sku',$product_query)->select('total_sales','sku')->get();
//            foreach ($lastYearData as $lastsale){
//                $lastsaleArr[$lastsale->sku] = $lastsale->total_sales;
//            }
//
//            $dataWhole_model = new Datawhole();
//            foreach ($list as $val) {
//                //父asin，fusku，asin
//                $val->asin = '';
//                $val->fnsku = '';
//                $val->father_asin = '';
//                if(isset($productdetail[$val->sku])){
//                    $val->asin = $productdetail[$val->sku]->asin;
//                    $val->fnsku = $productdetail[$val->sku]->fnsku;
//                    $val->father_asin = $productdetail[$val->sku]->parent_asin;
//                }
//                if(isset($productdetail[$val->old_sku])){
//                    $val->asin = $productdetail[$val->old_sku]->asin;
//                    $val->fnsku = $productdetail[$val->old_sku]->fnsku;
//                    $val->father_asin = $productdetail[$val->old_sku]->parent_asin;
//                }
//                $sku = $val->sku;
//                $custom_sku = $val->custom_sku;
//                // $category_id = $val->category_id;
////                if(!$val->img){
////                    if($val->old_custom_sku){
////                        $saihedetail = DB::table('saihe_product')->where('client_sku',$val->old_custom_sku)->select('small_image_url')->first();
////                    }else{
////                        $saihedetail = DB::table('saihe_product')->where('client_sku',$val->custom_sku)->select('small_image_url')->first();
////                    }
////                    if($saihedetail){
////                        $val->img = $saihedetail->small_image_url;
////                    }
////                }
//                $val->img = $this->GetCustomskuImg($val->custom_sku);
//
//                $sales_status = $val->sales_status;
//                //查找品类
//                $val->one_cate = '';
//                $oneres = $this->GetCategory($val->one_cate_id);
//                $val->one_cate = $oneres['name'];
//                $val->two_cate = '';
//                $twores = $this->GetCategory($val->two_cate_id);
//                $val->two_cate = $twores['name'];
//                $val->three_cate = '';
//                $threeres = $this->GetCategory($val->three_cate_id);
//                $val->three_cate = $threeres['name'];
//
//                //店铺名
//                $val->shop_name = '';
//                $shopres = $this->GetShop($val->shop_id);
//                $val->shop_name = $shopres['shop_name'];
//
//                //运营人员
//                $val->operate_user = '';
//                $users = $this->GetUsers($val->operate_user_id);
//                $val->operate_user = $users['account'];
//
//
//                //运营人
//                $val->user = '';
//                $userss = $this->GetUsers($val->user_id);
//                $val->user = $userss['account'];
//
//                // if (array_key_exists($category_id, $categoryName)) {
//                //     $val->category_name = $categoryName[$category_id];
//                // } else {
//                //     $val->category_name = '';
//                // }
//                //查找销售款式
//                if (array_key_exists($sales_status, $statusName)) {
//                    $val->category_status = $statusName[$sales_status];
//                } else {
//                    $val->category_status = '';
//                }
//                //库存
//                $val->tongAn_inventory = null;//同安fba仓库存
//                $val->self_delivery_inventory = null;//同安自发货仓库存
//                $val->in_warehouse_inventory = null;//fba在仓库存
//                $val->reserved_inventory = null;//预留库存
//                $val->in_road_inventory = null;//在途库存
//                $val->tongAn_deduct_inventory = null;//同安仓预扣库存
//
//
//
//                $getSaiheInventoryByOtherres['custom_sku'][0] = $val->custom_sku;
//                $getSaiheInventoryByOtherres['custom_sku'][1] = $val->old_custom_sku;
//                // var_dump( $getInventoryByOtherres);
//                $saihe_inventory = $this->getSaiheInventoryBycusSku($getSaiheInventoryByOtherres);
//                $val->tongAn_inventory = $saihe_inventory['tongAn_inventory'] ?? 0;
//                $val->quanzhou_inventory = $saihe_inventory['quanzhou_inventory'] ?? 0;
//
//                $getInventoryByOtherres['sku'][0] = $sku;
//                $getInventoryByOtherres['sku'][1] = $val->old_sku;
//                // var_dump( $getInventoryByOtherres);
//                $p_sku = $val->sku;
//                if($val->old_sku){
//                    $p_sku = $val->old_sku;
//                }
//                $inventory = Db::table('product_detail')->where('sellersku',$p_sku)->first();
//                // $inventory = $this->getInventoryByOther_buhuo($getInventoryByOtherres);
//                // $val->self_delivery_inventory = $inventory['self_delivery_inventory'] ?? 01;
//                $val->in_warehouse_inventory = 0;
//                $val->reserved_inventory = 0;
//                $val->in_road_inventory = 0;
//                if($inventory){
//                    $val->in_warehouse_inventory = $inventory->in_stock_num;
//                    $val->reserved_inventory = $inventory->in_bound_num;
//                    $val->in_road_inventory = $inventory->transfer_num;
//                }
//
//                $val->total_inventory = $val->in_warehouse_inventory + $val->reserved_inventory + $val->in_road_inventory;
//
//                                $tongAn_deduct_inventory =0;
//                                $quanzhou_deduct_inventory =  0;
//                                $cloud_deduct_inventory =  0;
//                // $getDeductInventoryres['sku'] = $val->custom_sku;
//                // $getDeductInventoryres['old_sku'] = $val->old_custom_sku;
//                // $getDeductInventoryres['warehouse'] = 1;
//                // //同安补货计划数量合计
//                // $tongAn_deduct_inventory = $this->getDeductInventory($getDeductInventoryres) ?? 0;
//                // //泉州补货计划数量合计
//                // $getDeductInventoryres2['sku'] = $val->custom_sku;
//                // $getDeductInventoryres2['old_sku'] = $val->old_custom_sku;
//                // $getDeductInventoryres2['warehouse'] = 2;
//                // $quanzhou_deduct_inventory = $this->getDeductInventory($getDeductInventoryres2) ?? 0;
//                // //云仓补货计划数量合计
//                // $getDeductInventoryres3['sku'] = $val->custom_sku;
//                // $getDeductInventoryres3['old_sku'] = $val->old_custom_sku;
//                // $getDeductInventoryres3['warehouse'] = 3;
//                // $cloud_deduct_inventory = $this->getDeductInventory($getDeductInventoryres3) ?? 0;
//
//                if ($tongAn_deduct_inventory > 0) {
//                    //如果该sku存在计划fab发货数量则扣除
//                    $val->tongAn_deduct_inventory = $val->tongAn_inventory - $tongAn_deduct_inventory;
//                } else {
//                    //如果不存在计划发货数量则等于同安仓库存
//                    $val->tongAn_deduct_inventory = $val->tongAn_inventory;
//                }
//
//                if ($quanzhou_deduct_inventory > 0) {
//                    //如果该sku存在计划fab发货数量则扣除
//                    $val->quanzhou_deduct_inventory = $val->quanzhou_inventory - $quanzhou_deduct_inventory;
//                } else {
//                    //如果不存在计划发货数量则等于泉州仓库存
//                    $val->quanzhou_deduct_inventory = $val->quanzhou_inventory;
//                }
//
//                if ($cloud_deduct_inventory > 0) {
//                    //如果该sku存在计划fab发货数量则扣除
//                    $val->cloud_deduct_inventory = $val->cloud_num - $cloud_deduct_inventory;
//                } else {
//                    //如果不存在计划发货数量则等于云仓库存
//                    $val->cloud_deduct_inventory = $val->cloud_num;
//                }
//
//                 //销量
//                //上周销量
//                $wholeParams['start_time'] = $startTime;
//                $wholeParams['end_time'] = $endTime;
//                $wholeParams['sku'] = $val->sku;
//                $wholeParams['old_sku'] = $val->old_sku;
//                $dataWhole = $this->getDatawholeByOtherNew($wholeParams);
//                $val->quantity_ordered = $dataWhole;
//                //上两周销量
//                $wholeParams['start_time'] = $startTimeTwo;
//                $wholeParams['end_time'] = $endTimeTwo;
//                $wholeParams['sku'] = $val->sku;
//                $wholeParams['old_sku'] = $val->old_sku;
//                $dataWholeTwo = $this->getDatawholeByOtherNew($wholeParams);
//                $val->before_quantity_ordered = $dataWholeTwo;
//                $year_sales = array();
//                //$val->before_quantity_ordered = 0;//上上周销量
//                $before2_quantity_ordered = 0;//上上上周销量
//                $before3_quantity_ordered = 0;//上上上上周销量
//
//                //本年总计销量
//                $wholeParams['start_time'] = $startTimeYear;
//                $wholeParams['end_time'] = $endTimeYear;
//                $wholeParams['sku'] = $val->sku;
//                $wholeParams['old_sku'] = $val->old_sku;
//                $dataWholeYear = $this->getDatawholeByOtherNew($wholeParams);
//                $val->year_total = $dataWholeYear;
//                //根据sku找去年销量
//                if (array_key_exists($val->sku, $lastsaleArr)) {
//                    $val->lastyear_sales = $lastsaleArr[$val->sku];
//                }else{
//                    $val->lastyear_sales = 0;
//                }
//                $val->last_year_daySales = round($val->lastyear_sales / 365, 2);//去年日销
//
//                //近一月合计销量
//                $wholeParams['start_time'] = $startTimeMonth;
//                $wholeParams['end_time'] = $endTimeMonth;
//                $wholeParams['sku'] = $val->sku;
//                $wholeParams['old_sku'] = $val->old_sku;
//                $dataWholeMoth = $this->getDatawholeByOtherNew($wholeParams);
//                $month_total = $dataWholeMoth;
//                //近两周合计销量
//                $val->total_sales = $val->quantity_ordered + $val->before_quantity_ordered;
//                //本周日销
//                $val->this_week_daysales = 0;
//                $this_weekDaysales = round($val->quantity_ordered / $thisDaySum, 2);
//                if ($this_weekDaysales > 0) $val->this_week_daysales = $this_weekDaysales;
//                //近两周日销
//                $val->week_daysales = 0;
//                //近一月日销
//                $this_monthDaysales = round($month_total / $lastDay, 2);
//                if ($val->total_sales != 0) $val->week_daysales = round(($val->total_sales) / $daySum, 2);
//                //库存可周转天数
//                if ($val->total_inventory != 0 && $val->week_daysales == 0) {
//                    $val->inventory_turnover = 999;
//                } elseif ($val->total_inventory == 0 && $val->week_daysales == 0) {
//                    $val->inventory_turnover = -1;
//                } elseif ($val->total_inventory == 0 && $val->week_daysales != 0) {
//                    $val->inventory_turnover = 0;
//                } else {
//                    if ($sales_status == 1) {  //爆款
//                        $val->inventory_turnover = $this->inventoryTurnoverStatus($val->total_inventory, $val->this_week_daysales, $val->plan_multiple);
//                    } elseif ($sales_status == 2) {  //利润款
//                        $val->inventory_turnover = $this->inventoryTurnoverStatus($val->total_inventory, $val->week_daysales, $val->plan_multiple);
//                    } elseif ($sales_status == 3) {   //清仓款
//                        $val->inventory_turnover = $this->inventoryTurnoverStatus($val->total_inventory, $this_monthDaysales, $val->plan_multiple);
//                    } else {
//                        $val->inventory_turnover = $this->inventoryTurnoverStatus($val->total_inventory, $val->week_daysales, $val->plan_multiple);
//                    }
//                }
//                //补货建议
//                $val->courier = 0;//补货建议快递
//                $val->air = 0;//补货建议空运
//                $val->shipping = 0;//补货建议海运
//                if($val->sales_status){
//                    $ReplenData['sales_status'] = $val->sales_status;
//                }else{
//                    $ReplenData['sales_status'] = 2;
//                }
//                $ReplenData['this_weekDaysales'] = $this_weekDaysales; //近1周日销
//                $ReplenData['plan_multiple'] = $val->plan_multiple; //销售计划增长倍数
//                $ReplenData['total_inventory'] = $val->total_inventory; //total_inventory
//                $ReplenData['inventory_turnover'] = $val->inventory_turnover; //在库可销售天数
//                $ReplenData['courier'] = 0; //快递
//                $ReplenData['week_daysales'] = $val->week_daysales; //近2周日销
//                $ReplenData['this_monthDaysales'] = $this_monthDaysales; //近1个月日销
//
//                $Replen = $this->getReplen($ReplenData);
////                $local_inventory = $val->tongAn_inventory + $val->quanzhou_inventory + $val->cloud_num;
//                $val->courier = $Replen['courier'] ;//补货建议快递
//
//                $val->air = $Replen['air'];//补货建议空运
//                $val->shipping = $Replen['shipping'];//补货建议海运
//                $val->replenishment_total = $Replen['replenishment_total'];//补货合计
//                $val->shipping_num = 0;
//                $val->air_num = 0;
//                $val->courier_num = 0;
//
//
//                //补货提醒
//                /*if ($val->inventory_turnover >= 0 && $val->inventory_turnover < 60) {
//                    $val->buhuo_status = 1;
//                }
//                if ($val->inventory_turnover >= 60 && $val->inventory_turnover < 90) {
//                    $val->buhuo_status = 2;
//                }
//                if ($val->inventory_turnover > 90) {
//                    $val->buhuo_status = 3;
//                }*/
//                //新旧sku替换
//
//                if($val->old_sku){
//                    $val->sku = $val->old_sku;
//                }
//                if($val->old_custom_sku){
//                    $val->custom_sku = $val->old_custom_sku;
//                }
//                if($val->old_spu){
//                    $val->spu = $val->old_spu;
//                }
//                $val->orderTotal = 0;
//
//                $sizes = ['XXS','XS','S','M','L','XL','2XL','3XL','4XL','5XL','6XL','7XL','8XL'];
//                if($val->size && in_array($val->size,$sizes)){
//                    $thisSize = $val->size;
//
//                    //查询已下单数据
//                    $isOrder = DB::table('anok_contract_clothing')
//                        ->where('plan_id', '!=',0)
//                        ->where('goods_no', $val->spu)
//                        ->where('color_code',$val->color)
//                        ->select($thisSize)
//                        ->get();
//                    if(!empty($isOrder)){
//                        $isOrder = json_decode(json_encode($isOrder),true);
//                        foreach ($isOrder as $ord){
//                            $val->orderTotal += $ord[$thisSize];
//                        }
//                    }
//                }
//
//
//            }
//        }
//        if (isset($params['buhuo_plan_data']) && $params['buhuo_plan_data'] == 1) {
//            return $list;
//        }
//        if ($type == 2 && !empty($list)) {
//            $export_data['thisDate'] = date('Y-m-d',strtotime($startTime)) . '~' . date('Y-m-d',strtotime($endTime));
//            $export_data['beforeDate'] = date('Y-m-d',strtotime($startTimeTwo)) . '~' . date('Y-m-d',strtotime($endTimeTwo));
//            $export_data['data'] = json_encode($list);
//            return $export_data;
//            //$res = $this->amazon_warnExport($export_data);
////            return $res;
//        }
//        return [
//            'data' => $list,
//            'totalNum' => $totalNum,
//        ];
//
//    }



    //获取销量-新-单个sku
    public function getDatawholeByOtherNew($params)
    {

                
        $sku = $params['sku'];

        $sku_id = $this->GetSkuId($sku);
        DB::connection()->enableQueryLog();

        $wkData = Db::table('amazon_order_item')->whereNotIn('order_status',array('Canceled'))->where('sku_id',$sku_id);

            //根据sku


        // if (isset($params['old_sku'])) {
        //     $wkData = $wkData->orwhere('seller_sku',$params['old_sku']);
        // } 
            

        $todaystart = date('Y-m-d 00:00:00', time());//当天
        $todayend = date('Y-m-d 23:59:59', time());//当天
        //查询类型
        $start_time = isset($params['start_time']) ? $params['start_time'] : $todaystart;
        $end_time = isset($params['end_time']) ? $params['end_time'] : $todayend;
        $start_time = date('Y-m-d 00:00:00', strtotime($start_time));
        $end_time = date('Y-m-d 23:59:59', strtotime($end_time));
        $wkData = $wkData->whereBetween('amazon_time', [$start_time, $end_time])->get();

        $quantity_ordered = 0;
        foreach ($wkData as $value) {
            # code...
            $quantity_ordered+= $value->quantity_ordered;

        }
        return $quantity_ordered;
    }
    /**
     * 库存可周转天数--不包含日销量计算
     * @param $total_inventory    合计库存     固定，和sales_status无关
     * @param $week_daysales      日销数据     不固定，和sales_status有关
     * @param $plan_multiple      计划增长倍数   固定，和sales_status无关
     * @param $sales_status 1:爆款      2:利润款    3:清仓款
     * @return $inventory_turnover  库存可周转天数
     */
    public function inventoryTurnoverStatus($total_inventory, $week_daysales, $plan_multiple)
    {

        if ($total_inventory != 0 && $week_daysales == 0) {
            $inventory_turnover = 999;
        } elseif ($total_inventory == 0 && $week_daysales == 0) {
            $inventory_turnover = -1;
        } elseif ($total_inventory == 0 && $week_daysales != 0) {
            $inventory_turnover = 0;
        } else {
            $a = $week_daysales*$plan_multiple;
           $inventory_turnover = $a>0 ? round($total_inventory / $a) : 0;
        }

        return $inventory_turnover;  //库存可周转天数

    }

    /**
     * 库存可周转天数--包含日销量计算
     * @param $total_inventory    合计库存     固定，和sales_status无关
     * @param $week_daysales      日销数据     不固定，和sales_status有关
     * @param $plan_multiple      计划增长倍数   固定，和sales_status无关
     * @param $sales_status 1:爆款      2:利润款    3:清仓款
     * @param $month   统计某个月份数据       默认当月  例子：2022-05
     * @return $inventory_turnover  库存可周转天数
     */
    public function inventoryTurnover($total_inventory, $plan_multiple, $sales_status, $saleTotal, $month = false)
    {

        $week_daysales = $this->week_daysales($sales_status, $saleTotal, $month);

        return $this->inventoryTurnoverStatus($total_inventory, $week_daysales, $plan_multiple);
    }


    /**
     * 计算日销量
     * @param $sales_status 1:爆款      2:利润款    3:清仓款
     * @param $saleTotal     销量
     * @param $month     月份，默认当月    例子：2022-05
     */
    public function week_daysales($sales_status, $saleTotal, $month = false)
    {
        $week_daysales = 0;
        if ($sales_status == 1) {//爆款
            $week_daysales = $this->daySales($saleTotal);
        }
        if ($sales_status == 2) {//利润款
            $week_daysales = $this->daySalesTwo($saleTotal);
        }
        if ($sales_status == 3) {//清仓款

            if ($month == false) {
                $monthNum = date("t");  //当月
            } else {
                $monthday = $month . "-15";
                $monthNum = date("t", strtotime($monthday));
            }

            $week_daysales = $this->monthSales($saleTotal, $monthNum);
        }

        return $week_daysales;
    }


    /**
     * 日销计算--月份
     * @param int $monthDay
     * @param int $weekDay
     */
    public function monthSales($month_total, $monthDay = 30)
    {

        $this_monthDaysales = round($month_total / $monthDay, 2);
        return $this_monthDaysales;
    }

    /**
     * 日销计算--本周
     * @param int $monthDay
     * @param int $weekDay
     */
    public function daySales($quantity_ordered, $weekDay = 7)
    {
        $this_weekDaysales = round($quantity_ordered / $weekDay, 2);
        return $this_weekDaysales;
    }

    /**
     * 日销计算--近2周
     * @param int $monthDay
     * @param int $weekDay
     */
    public function daySalesTwo($quantity_ordered, $weekDayTwo = 14)
    {
        $this_weekDaysales = round($quantity_ordered / $weekDayTwo, 2);
        return $this_weekDaysales;
    }


    //获取库存
    public function getInventoryBySku($sku, $custom_sku)
    {

        $skuSql = "SELECT
                    asin,warehouse_id,good_num,api_update_time
                FROM
                    saihe_inventory 
                WHERE  client_sku = '$custom_sku'
                AND warehouse_id in (2,386) 
                ";
        $skuData = DB::select($skuSql);
        $inventory = array();
        if (!empty($skuData)) {
            $inventory['tongAn_inventory'] = 0;//同安fba仓库存
            $inventory['self_delivery_inventory'] = 0;//自发货仓库存
            foreach ($skuData as $val) {
                //仓库
                if ($val->warehouse_id == 2) {
                    //同安fba
                    $inventory['tongAn_inventory'] += $val->good_num;
                } else {
                    //自发货仓
                    $inventory['self_delivery_inventory'] += $val->good_num;
                }

            }
        }

        $AMZinventorySql = "SELECT
        in_stock_num,in_bound_num,transfer_num,update_time,fnsku
        FROM
            product_detail
        WHERE  sellersku = '$sku'                        
        ";
        $AMZinventory = DB::select($AMZinventorySql);
        $inventory['in_warehouse_inventory'] = 0;//fba在仓库存
        $inventory['reserved_inventory'] = 0;//预留库存
        $inventory['in_road_inventory'] = 0;//在途库存
        $inventory['fnsku'] = '';
        if (!empty($AMZinventory)) {
            foreach ($AMZinventory as $val) {
                //仓库
                $inventory['in_warehouse_inventory'] = $val->in_stock_num;
                $inventory['reserved_inventory'] = $val->transfer_num;
                $inventory['in_road_inventory'] = $val->in_bound_num;
                $inventory['fnsku'] = $val->fnsku;
            }
        }
        return $inventory;
    }

    public function getSaiheInventoryBycusSku($params){
        $skuData = Db::table('saihe_inventory')
        ->whereIn('warehouse_id',array(2,386,560));
        if (!empty($params['custom_sku'])) {
            // $sku_res = DB::table('self_sku as sk')->leftjoin('self_custom_sku as sc','sk.custom_sku','=','sc.custom_sku')->whereIn('sk.sku',$params['sku'])->orwhereIn('sk.old_sku',$params['sku'])->select('sc.custom_sku','sc.old_custom_sku')->get()->toArray();
            // $cusarr = array_column($sku_res,'custom_sku');
            // $old_cusarr = array_column($sku_res,'old_custom_sku');
            // $cusArr=array_merge($cusarr,$old_cusarr);
            // var_dump($cusArr);
            $skuData =  $skuData ->whereIn('client_sku',$params['custom_sku']);
        }
        $skuData = $skuData->select('client_sku','asin','warehouse_id','good_num','api_update_time')->get()->toArray();

        $inventory = array();
        $inventory['tongAn_inventory'] = 0;//同安仓库存
        $inventory['quanzhou_inventory']= 0;//泉州仓库存

        if (!empty($skuData)) {
            foreach ($skuData as $val) {
                if($val->warehouse_id==560){
                    $inventory['quanzhou_inventory'] += $val->good_num;
                }
                if($val->warehouse_id==2||$val->warehouse_id==386){
                    $inventory['tongAn_inventory'] += $val->good_num;
                }
            }
        }

        return $inventory;

    }

    //获取海外仓库存
    public function getInventoryByOther_buhuo($params){
    $AMZinventory = Db::table('product_detail as a')->leftjoin('self_spu as sp','sp.spu', '=', 'a.spu');
    //根据sku
    if (!empty($params['sku'])) {
        if (is_array($params['sku'])) {
            $AMZinventory = $AMZinventory->whereIn('a.sellersku',$params['sku']);

        }
    }
    //根据分类
    if (!empty($params['one_cate_id'])) {
        $AMZinventory = $AMZinventory->where('sp.one_cate_id',$params['one_cate_id']);
    }
    if (!empty($params['two_cate_id'])) {
        $AMZinventory = $AMZinventory->where('sp.two_cate_id',$params['two_cate_id']);
    }
    if (!empty($params['three_cate_id'])) {
        $AMZinventory = $AMZinventory->where('sp.three_cate_id',$params['three_cate_id']);
    }
    //根据店铺
    if (!empty($params['shop_id'])) {
        $AMZinventory = $AMZinventory->where('a.shop_id',$params['shop_id']);
    }
    //根据运营
    if (!empty($params['user_id'])) {
        $AMZinventory = $AMZinventory->where('a.user_id',$params['user_id']);
    }
    //根据spu
    if (!empty($params['spu'])) {
        $AMZinventory = $AMZinventory->where('sp.spu',$params['spu'])->orwhere('sp.old_spu',$params['spu']);
    }



    $AMZinventory = $AMZinventory->select()->get()->toArray();

    $inventory['in_warehouse_inventory'] = 0;//fba在仓库存
    $inventory['reserved_inventory'] = 0;//预留库存
    $inventory['in_road_inventory'] = 0;//在途库存
    if (!empty($AMZinventory)) {
        foreach ($AMZinventory as $val) {
            //仓库 
            $inventory['in_warehouse_inventory'] = $val->in_stock_num;
            $inventory['reserved_inventory'] = $val->transfer_num;
            $inventory['in_road_inventory'] = $val->in_bound_num;
        }
    }
    return $inventory;
    }

    //获取库存-更改字段
    public function getInventoryByOther($params)
    {
        
        $AMZinventory = Db::table('product_detail as a')->leftjoin('self_spu as sp','sp.spu', '=', 'a.spu');

            //根据sku
        if (!empty($params['sku'])) {
            //param_style==1时为 getDatawholeCustoms()、getDatawholeCustomsSku方法查询 where in sku
            $skuData = Db::table('saihe_inventory')
            ->whereIn('warehouse_id',array(2,386,560));
            if (is_array($params['sku'])) {
                $sku_res = DB::table('self_sku as sk')->leftjoin('self_custom_sku as sc','sk.custom_sku','=','sc.custom_sku')->whereIn('sk.sku',$params['sku'])->orwhereIn('sk.old_sku',$params['sku'])->select('sc.custom_sku','sc.old_custom_sku')->get()->toArray();
                $cusarr = array_column($sku_res,'custom_sku');
                $old_cusarr = array_column($sku_res,'old_custom_sku');
                $cusArr=array_merge($cusarr,$old_cusarr);
                // var_dump($cusArr);
                $skuData =  $skuData ->whereIn('client_sku',$cusArr);
                $AMZinventory = $AMZinventory->whereIn('a.sellersku',$params['sku']);
                // $where .= " and b.order_source_sku in ({$params['sku']}) ";
                // $bwhere .= " and sellersku in ({$params['sku']}) ";
            }

        }else{
            $skuData = Db::table('saihe_inventory as a')
            ->leftjoin('saihe_product_detail as b','a.sku','=','b.saihe_sku')
            ->leftjoin('self_spu as sp','sp.spu','=','a.spu')
            ->whereIn('a.warehouse_id',array(2,386,560));
          

        }

  

        $AMZinventory = Db::table('product_detail as a')->leftjoin('self_spu as sp','sp.spu', '=', 'a.spu');
        //根据分类
        if (!empty($params['one_cate_id'])) {
            $skuData =  $skuData ->where('sp.one_cate_id',$params['one_cate_id']);
            $AMZinventory = $AMZinventory->where('sp.one_cate_id',$params['one_cate_id']);
        }
        if (!empty($params['two_cate_id'])) {
            $skuData =  $skuData ->where('sp.two_cate_id',$params['two_cate_id']);
            $AMZinventory = $AMZinventory->where('sp.two_cate_id',$params['two_cate_id']);
        }
        if (!empty($params['three_cate_id'])) {
            $skuData =  $skuData ->where('sp.three_cate_id',$params['three_cate_id']);
            $AMZinventory = $AMZinventory->where('sp.three_cate_id',$params['three_cate_id']);
        }
        //根据店铺
        if (!empty($params['shop_id'])) {
            $skuData =  $skuData ->where('b.shop_id',$params['shop_id']);
            $AMZinventory = $AMZinventory->where('a.shop_id',$params['shop_id']);
        }
        //根据运营
        if (!empty($params['user_id'])) {
            $skuData =  $skuData ->where('b.user_id',$params['user_id']);
            $AMZinventory = $AMZinventory->where('a.user_id',$params['user_id']);
        }
        //根据spu
        if (!empty($params['spu'])) {
            $skuData =  $skuData ->where('sp.spu',$params['spu'])->orwhere('sp.old_spu',$params['spu']);
            $AMZinventory = $AMZinventory->where('sp.spu',$params['spu'])->orwhere('sp.old_spu',$params['spu']);
        }


        if (empty($params['sku'])) {
            $skuData = $skuData->select('a.client_sku','a.asin','a.warehouse_id','a.good_num','a.api_update_time')->get()->toArray();
        }else{
            $skuData = $skuData->select('client_sku','asin','warehouse_id','good_num','api_update_time')->get()->toArray();
                
        }
        
    
        $AMZinventory = $AMZinventory->select()->get()->toArray();

        // $skuSql = "SELECT DISTINCT(b.client_sku),
        // a.asin,a.warehouse_id,a.good_num,a.api_update_time
        // FROM
        //     saihe_inventory a
        // LEFT JOIN saihe_product_detail b ON a.sku = b.saihe_sku
        // WHERE  
        //     $where
        // AND 
        // a.warehouse_id in (2,386)";

        // SELECT
        // a.asin,a.warehouse_id,a.good_num,a.api_update_time
        // FROM
        // saihe_inventory a
        // LEFT JOIN saihe_product_detail b ON a.sku = b.saihe_sku
        // WHERE
        // 1=1 and b.category_id = 20
        // AND
        // a.warehouse_id in (2,386)
        //运行时间 0.097
        // $skuData = DB::select($skuSql);
        $inventory = array();
        $inventory['tongAn_inventory'] = 0;//同安仓库存
        $inventory['quanzhou_inventory']= 0;//泉州仓库存

        if (!empty($skuData)) {
            foreach ($skuData as $val) {
                if($val->warehouse_id==560){
                    $inventory['quanzhou_inventory'] += $val->good_num;
                }
                if($val->warehouse_id==2||$val->warehouse_id==386){
                    $inventory['tongAn_inventory'] += $val->good_num;
                }
            }
        }

        // $AMZinventorySql = "SELECT
        // sum(instock_supply_quantity) as instock_supply_quantity,sum(in_bound_num) as in_bound_num,sum(transfer_num) as transfer_num,update_time
        // FROM
        // product_detail
        // WHERE  
        //     $bwhere";
        // SELECT
        // instock_supply_quantity,in_bound_num,transfer_num,update_time
        // FROM
        // product_detail
        // WHERE
        // 1=1 and category_id = 20
        //运行时间 0.045
        // var_dump($AMZinventorySql);

        // $AMZinventory = DB::select($AMZinventorySql);
        $inventory['in_warehouse_inventory'] = 0;//fba在仓库存
        $inventory['reserved_inventory'] = 0;//预留库存
        $inventory['in_road_inventory'] = 0;//在途库存
        if (!empty($AMZinventory)) {
            foreach ($AMZinventory as $val) {
                //仓库 
                $inventory['in_warehouse_inventory'] = $val->in_stock_num;
                $inventory['reserved_inventory'] = $val->transfer_num;
                $inventory['in_road_inventory'] = $val->in_bound_num;
            }
        }
        return $inventory;
    }

    /**
     * 计划发货数量总和
     *
     * @param [sting] $params
     * @return void
     */
    public function getDeductInventory($params)
    {
        if(isset($params['sku'])){
            $sku = $params['sku'];
            if(isset($params['old_sku'])){
                $old_sku = $params['old_sku'];
            }else{
                $old_sku = $params['sku'];
            }
        }else{
            $sku = $params;
            $skus = DB::table('self_custom_sku')->where('custom_sku',$sku)->orwhere('old_custom_sku',$sku)->first();
            if($skus){
                $old_sku = $skus->old_sku??$skus->sku;
            }else{
                $old_sku = $sku;
            }
        }
//                DB::connection()->enableQueryLog();
        $tongAn_deduct = DB::table('amazon_buhuo_request as a')
            ->leftJoin('amazon_buhuo_detail as b','a.id','=','b.request_id');


        $tongAn_deduct = $tongAn_deduct->where(function ($query) use($sku,$old_sku){
                $query->where('b.custom_sku',$sku)->orWhere('b.custom_sku',$old_sku);
            });
        if(isset($params['warehouse'])){
            $tongAn_deduct = $tongAn_deduct->where('a.warehouse',$params['warehouse']);
        }
        $tongAn_deduct = $tongAn_deduct->whereIn('a.request_status',[3,4,5,6,7])->select('request_num')->get()->toArray();

        $count = 0;
        if(!empty($tongAn_deduct)){
            foreach ($tongAn_deduct as $deduct) {
                $count += $deduct->request_num;
            }
        }

        return $count;
    }

    /**
     * 补货建议
     *
     * @param [array] $params
     * @return void
     */
    public function getReplen($params)
    {
        $sales_status = $params['sales_status'];
        $this_weekDaysales = $params['this_weekDaysales']; //近1周日销
        $plan_multiple = $params['plan_multiple']; //销售计划增长倍数
        $total_inventory = $params['total_inventory']; //total_inventory
        $inventory_turnover = $params['inventory_turnover']; //在库可销售天数
        $courier = $params['courier']; //快递
        $week_daysales = $params['week_daysales']; //近2周日销
        $this_monthDaysales = $params['this_monthDaysales']; //近1个月日销

        if ($sales_status == 1 || $sales_status == 2) {
            if ($sales_status == 1) {
                //爆款补货建议合计:近1周日销*销售计划增长倍数（运营可调整）*60天-库存合计
                $replenishment_total1 = round($this_weekDaysales * $plan_multiple * 60 - $total_inventory);
                $replenishment_total = $replenishment_total1 > 0 ? $replenishment_total1 : 0;
                //在库可销售天数<10,快递补货数量=近1周日销*10
                if ($inventory_turnover < 10) $courier = round($this_weekDaysales * 10);
                //空运=近1周日销*销售计划增长倍数*40天-库存合计-快递
                $air = round($this_weekDaysales * $plan_multiple * 40 - $total_inventory - $courier);
                $air = $air > 0 ? $air : 0;
            }
            if ($sales_status == 2) {
                //基础款补货建议合计:近2周日销*60天*销售计划增长倍数（运营可调整）-库存合计
                $replenishment_total2 = round($week_daysales * $plan_multiple * 60 - $total_inventory);
                $replenishment_total = $replenishment_total2 > 0 ? $replenishment_total2 : 0;
                //在库可销售天数<10,快递补货数量=近2周日销*10
                if ($inventory_turnover < 10) $courier = round($week_daysales * 10);
                //空运=近2周日销*销售计划增长倍数*40天-库存合计-快递
                $air = round($week_daysales * $plan_multiple * 40 - $total_inventory - $courier);
                $air = $air > 0 ? $air : 0;
            }
            //需补货总量-空运数量-快递数量
            $shipping = $replenishment_total - $air - $courier;
            $shipping = $shipping > 0 ? $shipping : 0;
        } else {
            //清仓款补货建议合计:只能补海运=近1个月日销*60天-库存合计
            $replenishment_total = round($this_monthDaysales * 60 - $total_inventory);
            $replenishment_total = $replenishment_total > 0 ? $replenishment_total : 0;
            $shipping = $replenishment_total;
            $air = 0;
        }
        $return['courier'] = $courier;//补货建议快递
        $return['air'] = $air;//补货建议空运
        $return['shipping'] = $shipping;//补货建议海运
        $return['replenishment_total'] = $replenishment_total; //补货合计
        return $return;
    }

    //新增sku
    public function addSku($params)
    {

        if (isset($params['shop_id'])) {
            $add['shop_id'] = $params['shop_id'];
        }
        if (isset($params['user_id'])) {
            $add['user_id'] = $params['user_id'];
        }
        if (isset($params['sku'])) {
            $add['sku'] = $params['sku'];
            $skulist = Db::table('amazon_skulist')
                ->where('sku', $add['sku'])
                ->first();
            if ($skulist) {
                return [
                    'type' => 'error',
                    'msg' => '该sku已存在'
                ];
            }
        } else {
            return [
                'type' => 'error',
                'msg' => 'sku为必填项'
            ];
        }
        if (isset($params['spu'])) {
            $add['spu'] = $params['spu'];
        }
        if (isset($params['category_id'])) {
            $add['category_id'] = $params['category_id'];
        }
        if (isset($params['sales_status'])) {
            $add['sales_status'] = $params['sales_status'];
        }
        if (isset($params['goods_style'])) {
            $add['goods_style'] = $params['goods_style'];
        }
        if (isset($params['gender'])) {
            $add['gender'] = $params['gender'];
        }

        $add['status'] = 1;
        $insert = Db::table('amazon_skulist')->insert($add);
        if ($insert) {
            return [
                'type' => 'success',
                'data' => $insert
            ];
        }

    }

    //修改sku
    public function updateSku($params)
    {

        if (isset($params['shop_id'])) {
            $add['shop_id'] = $params['shop_id'];
        }
        if (isset($params['user_id'])) {
            $add['user_id'] = $params['user_id'];
        }
        if (isset($params['sku'])) {
            $add['sku'] = $params['sku'];
        } else {
            return [
                'type' => 'error',
                'msg' => 'sku为必填项'
            ];
        }
        if (isset($params['spu'])) {
            $add['spu'] = $params['spu'];
            $skures = Db::table('amazon_skulist')->where('sku', $add['sku'])->first();
            if($add['spu']!=$skures->spu){
                if(isset($skures->custom_sku)){
                    $saiheadd['product_group_sku'] = $add['spu'];
                    $saiheupdate = Db::table('saihe_product')->where('client_sku', $skures->custom_sku)->update($saiheadd);
                }
            }
        }
        if (isset($params['category_id'])) {
            $add['category_id'] = $params['category_id'];
        }
        if (isset($params['sales_status'])) {
            $add['sales_status'] = $params['sales_status'];
        }
        if (isset($params['goods_style'])) {
            $add['goods_style'] = $params['goods_style'];
        }
        if (isset($params['gender'])) {
            $add['gender'] = $params['gender'];
        }
        if (isset($params['status'])) {
            $add['status'] = $params['status'];
        }
        if (isset($params['father_asin'])) {
            $add['father_asin'] = $params['father_asin'];
        }
        if (isset($params['asin'])) {
            $add['asin'] = $params['asin'];
        }
        if (isset($params['fnsku'])) {
            $add['fnsku'] = $params['fnsku'];
        }
        if (isset($params['img'])) {
            $add['img'] = $params['img'];
        }


        $update = Db::table('amazon_skulist')->where('sku', $add['sku'])->update($add);
        if ($update) {
            return [
                'type' => 'success',
                'data' => $update
            ];
        }

    }

    public function updateSkulist($params)
    {
        $sku = $params['sku'];
        Redis::Lpush('onesku', $sku);
        return [
            'data' => []
        ];
        $skures = Db::table('amazon_skulist')->where('sku', $sku)->first();
        $params['shop_id'] = $skures->shop_id;
        $user_id =  $skures->user_id;
        $amazon_sku = $this->amazon_sku($params);
        $data = $amazon_sku['GetMatchingProductForIdResult'];
        if (isset($data['Error'])) {
            return [
                'type' => 'error',
                'msg' => $data['Error']['Message'] . ',请十分钟后再请求'
            ];

        }
        $parent_asin = $data['Products']['Product']['Relationships']['VariationParent']['Identifiers']['MarketplaceASIN']['ASIN']??'';
        $asin = $data['Products']['Product']['Identifiers']['MarketplaceASIN']['ASIN']??'';
        $itemAttributes = $data['Products']['Product']['AttributeSets']['ItemAttributes']??'';
        $brand = $itemAttributes['Brand']??'';
        $color = $itemAttributes['Color']??'';
        $binding = $itemAttributes['Binding']??'';
        $department = $itemAttributes['Department']??'';
        $productGroup = $itemAttributes['ProductGroup']??'';
        $productTypeName = $itemAttributes['ProductTypeName']??'';
        $smallImage = $itemAttributes['SmallImage']['URL']??'';
        $title = $itemAttributes['Title']??'';
        $size = $itemAttributes['Size']??'';
        $time = time();

        $product_detail_data = Db::table('product_detail')
        ->select('small_image', 'fnsku', 'asin')
        ->where('sellersku', $sku)
        ->first();

        $client_img = '';
        $asin = $asin;
        $product_detail_add['parent_asin'] =  $parent_asin;
        $product_detail_add['asin'] =  $asin;
        $product_detail_add['brand'] =  $brand;
        $product_detail_add['color'] =  $color;
        $product_detail_add['binding'] =  $binding;
        $product_detail_add['department'] =  $department;
        $product_detail_add['product_group'] =  $productGroup;
        $product_detail_add['product_type_name'] =  $productTypeName;
        $product_detail_add['small_image'] =  $smallImage;
        $product_detail_add['title'] =  $title;
        $product_detail_add['size'] = $size;
        $product_detail_add['update_time'] =  $time;

        if (!$product_detail_data) {
            $product_detail_add['sellersku'] =  $sku;
            $product_detail_add['shop_id'] =  $params['shop_id'];
            $product_detail_add['platform_id'] =  5;
            $product_detail_add['user_id'] = $user_id;
            $product_detail_add['is_query'] =  1;
            Db::table('product_detail')->insert($product_detail_add);
            $fnsku = '';
            $father_asin = '';
        } else {
            $update = Db::table('product_detail')->where('sellersku', $sku)->update($product_detail_add);
            $fnsku = $product_detail_data->fnsku;
        }

        $client_sku = '';
//        $clientSql = "SELECT
//                        a.client_sku
//                    FROM
//                        saihe_product a
//                    LEFT JOIN saihe_product_detail b ON a.sku = b.saihe_sku
//                    WHERE  b.order_source_sku = '$sku'
//                    ";
//        $client = DB::select($clientSql);
//
//        if (!empty($client)) {
//            $client_sku = $client[0]->client_sku;//库存sku
//        }

        $product_name_data = Db::table('saihe_product_detail as spd')
            ->leftJoin('saihe_product as sp', 'sp.sku', '=', 'spd.saihe_sku')
            ->select('sp.product_name_cn', 'sp.client_sku')
            ->where('spd.order_source_sku', $sku)
            ->get();
        $product_name = '';
        if (isset($product_name_data[0])) {
            if(isset($product_name_data[0]->client_sku)){
                $client_sku = $product_name_data[0]->client_sku;
            }
            if(isset($product_name_data[0]->product_name_cn)){
                $product_name = strstr($product_name_data[0]->product_name_cn, $product_name_data[0]->client_sku);
                }
            if ($product_name === false) {
                $product_name = $product_name_data[0]->product_name_cn;
            }
        }
        $sku_data['fnsku'] = $fnsku;
        $sku_data['asin'] = $asin;
        $sku_data['father_asin'] = $parent_asin;
        $sku_data['sku'] = $sku;
        $sku_data['custom_sku'] = $client_sku;
//        $sku_data['img'] = $client_img;
        $sku_data['product_name'] = $product_name;
        $sku_data['time'] = time();
        $update = Db::table('amazon_skulist')->where('sku', $sku)->update($sku_data);
        if ($update) {
            return [
                'data' => $sku_data
            ];
        }
    }


    public function updateSkulistImg($params){

        $sku = $params['sku'];
        $img = $params['img']??'';
        $sku_data['img'] = $img;
        foreach ($sku as $v) {
            # code...
            $update = Db::table('amazon_skulist')->where('sku', $v)->update($sku_data);
        }

        return [
            'type' =>'success',
            'data' => $sku_data
        ];


    }

    public function getAmazonExcel($params)
    {
        $where = "1 = 1";
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $page = $this->getLimitParam($page, $limit);
        if ($params['type'] == 'amazon_sales') {
            $sql = "select * from amazon_sale_percentage  ORDER BY id desc LIMIT $page,$limit";
            $data = DB::select($sql);
            $totalNum = db::select("SELECT count(1) as total from amazon_sale_percentage")[0]->total;
        }
        if ($params['type'] == 'amazon_category') {
            if (!empty($params['category_id'])) {
                foreach ($params['category_id'] as $cateVal) {
                    $category_id[] = "'" . $cateVal . "'";
                }
                $category_id = implode(",", $category_id);
                $where .= " and a.category_id in ($category_id)";
            }
            if (!empty($params['store'])) {
                $where .= " and a.shop_id = {$params['store']}";
            }
            if (!empty($params['sale_status'])) {
                $where .= " and a.sales_status = {$params['sale_status']}";
            }

            if (!empty($params['sku'])) {
                if (strstr($params['sku'], '，')) {
                    $symbol = '，';
                } elseif (strstr($params['sku'], ',')) {
                    $symbol = ',';
                } else {
                    $symbol = '';
                }
                if ($symbol) {
                    $skuarray = explode($symbol,$params['sku']);
                    foreach ($skuarray as $key => $sku) {
                        $skus = Db::table('self_sku')->where('sku', $sku)->orwhere('old_sku', $sku)->first();
                        if($key==0){
                            
                            if($skus){
                                $old_sku = $skus->old_sku??$skus->sku;
                                $where .= " and a.sku like '%{$sku}%' or a.sku like '%{$old_sku}%' ";
                            }else{
                                $where .= " and a.sku like '%{$sku}%'  ";
                            }
                       }else{
                          
                            if($skus){
                                $old_sku = $skus->old_sku??$skus->sku;
                                $where .= " or a.sku like '%{$sku}%' or a.sku like '%{$old_sku}%' ";
                            }else{
                                $where .= " or a.sku like '%{$sku}%' ";
                            }
                       }
                    }
                }else {
                    $skus = Db::table('self_sku')->where('sku', $params['sku'])->orwhere('old_sku', $params['sku'])->first();
                    if($skus){
                        $old_sku = $skus->old_sku??$skus->sku;
                        $where .= " and a.sku like '%{$skus->sku}%' or a.sku like '%{$old_sku}%' ";
                    }else{
                        $where .= " and a.sku like '%{$params['sku']}%' ";
                    }
                   
                }
            }


            if (!empty($params['asin'])) {
                if (strstr($params['asin'], '，')) {
                    $symbol = '，';
                } elseif (strstr($params['asin'], ',')) {
                    $symbol = ',';
                } else {
                    $symbol = '';
                }
                if ($symbol) {
                    $asinarray = explode($symbol,$params['asin']);
                    foreach ($asinarray as $key => $sku) {
                        if($key==0){
                            $where .= " and a.asin like '%{$sku}%' ";
                       }else{
                            $where .= " or a.asin like '%{$sku}%' ";
                       }
                    }
                }else {
                    $where .= " and a.asin like '%{$params['asin']}%' ";
                }

            }


            if (!empty($params['custom_sku'])) {
                if (strstr($params['custom_sku'], '，')) {
                    $symbol = '，';
                } elseif (strstr($params['custom_sku'], ',')) {
                    $symbol = ',';
                } else {
                    $symbol = '';
                }
                if ($symbol) {
                    $custom_skuarray = explode($symbol,$params['custom_sku']);
                    foreach ($custom_skuarray as $key => $sku) {
                        if($key==0){
                            $where .= " and a.custom_sku like '%{$sku}%' ";
                       }else{
                            $where .= " or a.custom_sku like '%{$sku}%' ";
                       }
                    }
                }else {
                    $where .= " and a.custom_sku like '%{$params['custom_sku']}%' ";
                }
            }

            if (!empty($params['father_asin'])) {
                if (strstr($params['father_asin'], '，')) {
                    $symbol = '，';
                } elseif (strstr($params['father_asin'], ',')) {
                    $symbol = ',';
                } else {
                    $symbol = '';
                }
                if ($symbol) {
                    $father_asinarray = explode($symbol,$params['father_asin']);
                    foreach ($father_asinarray as $key => $sku) {
                        if($key==0){
                            $where .= " and a.father_asin like '%{$sku}%' ";
                       }else{
                            $where .= " or a.father_asin like '%{$sku}%' ";
                       }
                    }
                }else {
                    $where .= " and a.father_asin like '%{$params['father_asin']}%' ";
                }
            }


            if (!empty($params['spu'])) {
                if (strstr($params['spu'], '，')) {
                    $symbol = '，';
                } elseif (strstr($params['spu'], ',')) {
                    $symbol = ',';
                } else {
                    $symbol = '';
                }
                if ($symbol) {
                    $spuarray = explode($symbol,$params['spu']);
                    foreach ($spuarray as $key => $sku) {
                        if($key==0){
                            $where .= " and a.spu like '%{$sku}%' ";
                       }else{
                            $where .= " or a.spu like '%{$sku}%' ";
                       }
                    }
                } else {
                    $where .= " and a.spu like '%{$params['spu']}%' ";
                }
            }
            // if (!empty($params['sku'])) {
            //     if (strstr($params['sku'], '，')) {
            //         $symbol = '，';
            //     } elseif (strstr($params['sku'], ',')) {
            //         $symbol = ',';
            //     } else {
            //         $symbol = '';
            //     }
            //     if ($symbol) {
            //         $skuarray = explode($symbol,$params['sku']);
            //         foreach ($skuarray as $key => $sku) {
            //             if($key==0){
            //                 $where .= " and (a.sku like '%{$sku}%' or a.custom_sku like '%{$sku}%' or a.father_asin like '%{$sku}%')";
            //            }else{
            //                 $where .= " or (a.sku like '%{$sku}%' or a.custom_sku like '%{$sku}%' or a.father_asin like '%{$sku}%')";
            //            }
            //         }
            //     } else {
            //         $where .= " and (a.sku like '%{$params['sku']}%' or a.custom_sku like '%{$params['sku']}%' or a.father_asin like '%{$params['sku']}%')";
            //     }
            // }
            if (!empty($params['user_id'])) {
                $where .= " and a.user_id = {$params['user_id']} ";
            }
            if (!empty($params['style_id'])) {
                $where .= " and a.goods_style = {$params['style_id']} ";
            }
            $data_type = isset($params['data_type']) ? $params['data_type'] : null;
            if ($data_type == '0') {
                $where .= " and (a.category_id=0 or a.sales_status=0 or a.gender='' or a.user_id=0 or a.goods_style=0 or a.sales_status=0)";
            }
            if ($data_type == '1') {
                $where .= " and a.category_id!=0 and a.sales_status!=0 and a.gender!='' and a.user_id!=0 and a.goods_style!=0 and a.sales_status!=0";
            }

            // if (!empty($params['spu'])) {
            //     $where .= " and a.spu='{$params['spu']}'";
            // }
            if (!empty($params['product_name'])) {
                $where .= " and a.product_name like '%{$params['product_name']}%'";
            }

            $sql = "SELECT SQL_CALC_FOUND_ROWS
                    a.id,
                    a.sku,
                    a.asin,
                    a.product_name,
                    a.spu,
                    a.father_asin,
                    a.gender,
                    a.shop_id,
                    a.user_id,
                    a.category_id,
                    a.custom_sku,
                    a.goods_style,
                    a.sales_status,
                    a.img,
                    a.spu,     
                    a.asin,
                    a.fnsku,
                    a.product_name,
                    u.account,
                    b.product_typename,
                    d.category_status,
                    s.shop_name,
                    s.fba_warehouse_id,
                    a.status
                FROM
                    amazon_skulist a
                LEFT JOIN amazon_category b ON a.category_id = b.id
                LEFT JOIN amazon_category_status d ON a.sales_status = d.id
                LEFT JOIN users u ON a.user_id = u.Id         
                LEFT JOIN shop s ON a.shop_id = s.Id
                WHERE
                    $where
                order by a.sku desc 
                LIMIT $page,
                 $limit";

            $data = DB::select($sql);
            $totalNum = db::select("SELECT FOUND_ROWS() as total")[0]->total;
            foreach ($data as $val) {
                $sku = $val->sku;
                $custom_sku = $val->custom_sku;
                //获得当日凌晨的时间戳
                $today = strtotime(date("Y-m-d"), time());
                //根据sku找赛盒库存

                $val->tongAn_inventory = null;//同安fba仓库存
                $val->self_tongAn_inventory = null;//同安自发仓库存
                $val->in_warehouse_inventory = null;//fba在仓库存
                $val->reserved_inventory = null;//预留库存
                $val->in_road_inventory = null;//在途库存
                $inventory = $this->getInventoryBySku($sku, $custom_sku);

                $val->tongAn_inventory = $inventory['tongAn_inventory'] ?? 0;
                $val->self_tongAn_inventory = $inventory['self_delivery_inventory'] ?? 0;
                $val->in_warehouse_inventory = $inventory['in_warehouse_inventory'] ?? 0;
                $val->reserved_inventory = $inventory['reserved_inventory'] ?? 0;
                $val->in_road_inventory = $inventory['in_road_inventory'] ?? 0;
                $val->total_inventory = $val->in_warehouse_inventory + $val->reserved_inventory + $val->in_road_inventory;

                $skus = Db::table('self_custom_sku')->where('custom_sku', $custom_sku)->orwhere('old_custom_sku', $custom_sku)->first();

                $inventory_query['sku'] = $custom_sku;
                if($skus){
                    $inventory_query['old_sku'] = $skus->old_custom_sku??$skus->custom_sku;
                }

                $tongAn_deduct_inventory = $this->getDeductInventory($inventory_query) ?? 0;

                if ($tongAn_deduct_inventory > 0) {
                    //如果该sku存在计划fab发货数量则扣除
                    $val->tongAn_deduct_inventory = $val->tongAn_inventory - $tongAn_deduct_inventory;
                } else {
                    //如果不存在计划发货数量则等于同安fba仓库存
                    $val->tongAn_deduct_inventory = $val->tongAn_inventory;
                }

            }

        }
        if ($params['type'] == 'amazon_inventory') {
            $sql = "select SQL_CALC_FOUND_ROWS a.*,s.shop_name from amazon_inventory a left join shop s on a.shop_id=s.Id where $where ORDER BY a.id asc LIMIT $page,$limit";
            $data = DB::select($sql);
            $totalNum = db::select("SELECT FOUND_ROWS() as total")[0]->total;
        }

//        var_dump($data);die;

        return [
            'data' => $data,
            'totalNum' => $totalNum
        ];
    }


    public function getShopeeExcel($params)
    {
        $where = "1 = 1";
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $page = $this->getLimitParam($page, $limit);
        if ($params['type'] == 'goods_link') {
            $sql = "select SQL_CALC_FOUND_ROWS sl.*,s.shop_name from shopee_link sl left join shop s on sl.shop_id=s.Id where $where ORDER BY id desc LIMIT $page,$limit";
        }
        if ($params['type'] == 'goods_adv') {
            $sql = "select SQL_CALC_FOUND_ROWS sa.*,s.shop_name from shopee_adv sa left join shop s on sa.shop_id=s.Id where $where ORDER BY id desc LIMIT $page,$limit";
        }
        $data = DB::select($sql);
        $totalNum = db::select("SELECT FOUND_ROWS() as total")[0]->total;
        return [
            'data' => $data,
            'totalNum' => $totalNum
        ];
    }

    public function excelInsert($params)
    {
        $type = $params['type'];

        if ($type == 'amazon_sales') {
            $res = $this->excelInsertNew($params);
        } elseif ($type == 'amazon_category') {
            $res = $this->amazon_category_excel($params);
        } elseif ($type == 'amazon_2021total') {
            $res = $this->amazon_total_excel($params);
        } elseif ($type == 'shopee_adv' || $type == 'shopee_link') {
            if (empty($params['start_date']) || empty($params['end_date']) || empty($params['store'])) {
                return [
                    'type' => 'fail',
                    'msg' => '参数不足，请重新选择'
                ];
            }
            $month = $params['month'];
            $week = $params['week'];
            if ($week == '1') {
                $day = '01';
            } elseif ($week == '2') {
                $day = '08';
            } elseif ($week == '3') {
                $day = '15';
            } else {
                $day = '22';
            }
            $params['date'] = date("Y-" . $month . "-" . $day);
            if ($type == 'shopee_adv') {
                $res = $this->shopee_adv_excel($params);
            }
            if ($type == 'shopee_link') {
                $res = $this->shopee_link_excel($params);
            }
        } elseif ($type = 'addspu') {
            $res = $this->amazon_spu_excel($params);
        }

        return $res;
    }

    //亚马逊会话次数导入
    public function excelInsertNew($params)
    {

        $file = $params['file'];
        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        $store = $params['store'];
        if (empty($params['start_time']) || empty($params['end_time'])) {
            return [
                'type' => 'fail',
                'msg' => '参数不足，请重新选择'
            ];
        }

        $start_time = $params['start_time'];
        $end_time = $params['end_time'];

        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);

        $day = ceil(($end_time - $start_time) / 86400) + 1;

        // echo $day;
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }
        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);

        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        //循环插入流量数据
        $a = 0;
        $b = 0;
        $time = time();
        $jk = 0;
        $jobres = array();
        $jobres['day'] = $day;
        $jobres['start_time'] = $start_time;
        $jobres['end_time'] = $end_time;
        $err_arr = [];

        for ($j = 2; $j <= $allRow; $j++) {

            $father_asin = $Sheet->getCellByColumnAndRow(0, $j)->getValue();
            $son_asin = $Sheet->getCellByColumnAndRow(1, $j)->getValue();
            $product_name = $Sheet->getCellByColumnAndRow(2, $j)->getValue();
            $product_name = str_replace("'", " ", $product_name);
            $sku = $Sheet->getCellByColumnAndRow(3, $j)->getValue();
            // $session = $Sheet->getCellByColumnAndRow(4, $j)->getValue();
            // $session = str_replace(",","",$session);
            $session_percentage = $Sheet->getCellByColumnAndRow(5, $j)->getValue();
            $session_percentage = str_replace(",", "", $session_percentage);
            // $page_views = $Sheet->getCellByColumnAndRow(6, $j)->getValue();
            // $page_views=str_replace(",","",$page_views);
            // $page_views_percentage = $Sheet->getCellByColumnAndRow(7, $j)->getValue();
            // $page_views_percentage=str_replace(",","",$page_views_percentage);
            // $quantity_ordered = $Sheet->getCellByColumnAndRow(8, $j)->getValue();
            // $goods_session_percentage = $Sheet->getCellByColumnAndRow(9, $j)->getValue();
            // $goods_session_percentage = (float)$goods_session_percentage/100;
            // $quantity_sales = $Sheet->getCellByColumnAndRow(10, $j)->getValue();
            // $quantity_sales=str_replace(",","",$quantity_sales);
            // $quantity_sales=substr($quantity_sales,3);
            

            if ($sku && $session_percentage) {
                // $skuSql = "select * from amazon_skulist where `sku`='$sku'";
                // $checkSku = DB::select($skuSql);
                // if ($checkSku == null) {
                //     $addSql = "insert into amazon_skulist(`shop_id`,`sku`,`father_asin`,`asin`,`product_name`,`time`) values ('$store','$sku','$father_asin','$son_asin','$product_name','$time')";
                //     DB::insert($addSql);
                // }

                $skulist = Db::table('self_sku')->where('sku',$sku)->orwhere('old_sku',$sku)->first();

                if(!$skulist){
                    $err_arr['sku'][] = $sku;
                }else{
                    $spu = $skulist->spu ?? '';
                    $shop_id =  $store;
                    $category_id = 0;
                    $user_id = $skulist->user_id??0;
                    $session_percentage = round($session_percentage / $day, 3);
                    // $time = time();
    
                    $jobres[$jk]['sku'] = $sku;
                    $jobres[$jk]['custom_sku_id'] = $skulist->custom_sku_id??0;
                    $jobres[$jk]['sku_id'] = $skulist->id;
                    $jobres[$jk]['session_percentage'] = $session_percentage;
                    $jobres[$jk]['shop_id'] = $shop_id;
                    $jobres[$jk]['spu_id'] = $skulist->spu_id;
                    $jobres[$jk]['spu'] = $spu;
                    $jobres[$jk]['user_id'] = $user_id;
                    $jobres[$jk]['category_id'] = $category_id;
                    $jk++;
                }

            }


        }

        // if(count($err_arr)>=1){
        //     return [
        //         'type' => 'fail',
        //         'msg' => '导入失败，无此sku'.json_encode($err_arr)
        //     ];
        // }

        // return [
        //     'type' => 'success',
        //     'msg' => $jobres
        // ];
        $insert['shop_id'] =  $store;
        $shop_name = $this->GetShop($insert['shop_id'])['shop_name'];
        $insert['title'] = '['.$shop_name.']'.date('Y-m-d',$start_time).'-'.date('Y-m-d',$end_time);
        $insert['status'] = -1;
        $insert['msg'] = "等待开始";
        $insert['create_time'] = date('Y-m-d H:i:s',time());
        $insert['user_id'] = $params['find_user_id']??1;
        $task_id =  Db::table('amazon_sales_task')->insertGetId($insert);
        $jobres['task_id'] = $task_id;
        $job = new AmazonSalesController();
        try {
            $job::runJob($jobres);
        } catch(\Exception $e){
            return $this->back('导入队列失败', 500);
        }

 
        return [
            'type' => 'success',
            'msg' => '加入队列成功'
        ];


    }


       //excel 导出任务
    public function AmazonSalesTaskList($params){
        // $user_id = $params['user_id'];
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;


        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $totalNum=  DB::table('amazon_sales_task')->count();
        $list = DB::table('amazon_sales_task')->offset($page)->limit($limit)->orderby('id','desc')->get();
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];
    }


    //亚马逊会话次数导入
    public function excelInsertNew_bak($params)
    {

        $file = $params['file'];
        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        $store = $params['store'];
        if (empty($params['start_time']) || empty($params['end_time'])) {
            return [
                'type' => 'fail',
                'msg' => '参数不足，请重新选择'
            ];
        }

        $start_time = $params['start_time'];
        $end_time = $params['end_time'];

        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);

        $day = ceil(($end_time - $start_time) / 86400) + 1;

        // echo $day;
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }
        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);

        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        //循环插入流量数据
        $a = 0;
        $b = 0;
        $time = time();

        for ($j = 2; $j <= $allRow; $j++) {

            $father_asin = $Sheet->getCellByColumnAndRow(0, $j)->getValue();
            $son_asin = $Sheet->getCellByColumnAndRow(1, $j)->getValue();
            $product_name = $Sheet->getCellByColumnAndRow(2, $j)->getValue();
            $product_name = str_replace("'", " ", $product_name);
            $sku = $Sheet->getCellByColumnAndRow(3, $j)->getValue();
            // $session = $Sheet->getCellByColumnAndRow(4, $j)->getValue();
            // $session = str_replace(",","",$session);
            $session_percentage = $Sheet->getCellByColumnAndRow(5, $j)->getValue();
            $session_percentage = str_replace(",", "", $session_percentage);
            // $page_views = $Sheet->getCellByColumnAndRow(6, $j)->getValue();
            // $page_views=str_replace(",","",$page_views);
            // $page_views_percentage = $Sheet->getCellByColumnAndRow(7, $j)->getValue();
            // $page_views_percentage=str_replace(",","",$page_views_percentage);
            // $quantity_ordered = $Sheet->getCellByColumnAndRow(8, $j)->getValue();
            // $goods_session_percentage = $Sheet->getCellByColumnAndRow(9, $j)->getValue();
            // $goods_session_percentage = (float)$goods_session_percentage/100;
            // $quantity_sales = $Sheet->getCellByColumnAndRow(10, $j)->getValue();
            // $quantity_sales=str_replace(",","",$quantity_sales);
            // $quantity_sales=substr($quantity_sales,3);


            if ($sku && $session_percentage) {
                $skuSql = "select * from amazon_skulist where `sku`='$sku'";
                $checkSku = DB::select($skuSql);
                if ($checkSku == null) {
                    $addSql = "insert into amazon_skulist(`shop_id`,`sku`,`father_asin`,`asin`,`product_name`,`time`) values ('$store','$sku','$father_asin','$son_asin','$product_name','$time')";
                    DB::insert($addSql);
                }
                $spu = $checkSku[0]->spu ?? '';
                $shop_id = $store;
                $category_id = $checkSku[0]->category_id ?? '';
                $user_id = $checkSku[0]->user_id ?? '';
                $session_percentage = round($session_percentage / $day, 3);
                $time = time();
                for ($i = 0; $i < $day; $i++) {
                    # code...
                    $addtime = $i * 86400;
                    $start_date = date('Y-m-d', $start_time + $addtime);

                    $saleSql = "select * from amazon_sale_percentage where `sku`='$sku' and `ds`='$start_date' ";
                    $checkSaleSku = DB::select($saleSql);
                    if ($checkSaleSku) {
                        $id = $checkSaleSku[0]->id;
                        $updatesql = "UPDATE amazon_sale_percentage
                            SET `sku` = '$sku',
                             `session_percentage` = '$session_percentage',
                             `shop_id` = $shop_id,
                             `spu` = '$spu',
                             `user_id` = $user_id,
                             `category_id` = '$category_id',
                             `ds` = '$start_date',
                             `create_time` = '$time',
                             `update_time` = '$time'
                            WHERE
                                `id` = '$id'";
                        $result = DB::update($updatesql);
                        if (!$result) {
                            return [
                                'type' => 'fail',
                                'msg' => '导入失败，Excel文件错误'
                            ];
                        } else {
                            $b++;
                        }

                    } else {
                        $sql = "INSERT INTO amazon_sale_percentage (
                                `sku`,
                                `session_percentage`,
                                `shop_id`,
                                `spu`,
                                `user_id`,
                                `category_id`,
                                `ds`,
                                `create_time`,
                                `update_time`
                            )
                            VALUES
                                (
                                    '$sku',
                                    '$session_percentage',
                                    '$shop_id',
                                    '$spu',
                                    '$user_id',
                                    '$category_id',
                                    '$start_date',
                                    $time,
                                    $time
                                )";
                        $result = DB::insert($sql);
                        if (!$result) {
                            return [
                                'type' => 'fail',
                                'msg' => '导入失败，Excel文件错误'
                            ];
                        } else {
                            $a++;
                        }
                    }


                }
            }


        }
        return [
            'type' => 'success',
            'msg' => '导入成功，本次共导入' . $a . '条数据,更新' . $b . '条数据'
        ];


    }


    /*
      *  亚马逊2021年度汇总导入
      */
    public function amazon_total_excel($params)
    {
        $file = $params['file'];
        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }

        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);

        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        //循环插入流量数据
        $a = 0;
        $b = 0;
        $year = date('Y') - 1;
        for ($j = 2; $j <= $allRow; $j++) {
            $shop_name = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            $sku = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
            $total_order = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
            $select_shopid = DB::table('shop')->where('shop_name', '=', $shop_name)->select('Id')->get();
            if (!empty($sku)) {
                if ($select_shopid->isEmpty()) {
                    $shop_id = DB::table('shop')->insertGetId(['platform_id' => 5, 'shop_name' => $shop_name]);
                } else {
                    $shop_id = $select_shopid[0]->Id;
                }
                $select_skuid = DB::table('amazon_year_sale')->where('sku', '=', $sku)->where('year', '=', $year)->select('id')->get();
                if ($select_skuid->isEmpty()) {
                    $sku_id = $select_skuid[0]->id;
                    $result = DB::table('amazon_year_sale')->where('id', '=', $sku_id)->update(['total_sales' => $total_order]);
                    if ($result) $b++;
                } else {
                    $result = DB::table('amazon_year_sale')->insert(['shop_id' => $shop_id, 'sku' => $sku, 'total_sales' => $total_order, 'year' => $year]);
                    if ($result) $a++;
                }
            }
        }
        return [
            'type' => 'success',
            'msg' => '导入成功，本次共导入' . $a . '条数据,更新' . $b . '条数据'
        ];

    }

    /*
     *  亚马逊流量数据导入
     */
    public function amazon_sale_excel($params)
    {
        $file = $params['file'];
        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        $store = $params['store'];
        $date = $params['date'];
        $operation_id = $params['operation_id'];

        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }

        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);

        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        //循环插入流量数据
        $a = 0;
        $b = 0;
        $time = time();
        for ($j = 2; $j <= $allRow; $j++) {

            $father_asin = $Sheet->getCellByColumnAndRow(0, $j)->getValue();
            $son_asin = $Sheet->getCellByColumnAndRow(1, $j)->getValue();
//            $product_name = $Sheet->getCellByColumnAndRow(2, $j)->getValue();
//            $product_name = str_replace("'", " ", $product_name);
            $sku = $Sheet->getCellByColumnAndRow(3, $j)->getValue();
            $session = $Sheet->getCellByColumnAndRow(4, $j)->getValue();
            $session = str_replace(",", "", $session);
            $session_percentage = $Sheet->getCellByColumnAndRow(5, $j)->getValue();
            $session_percentage = str_replace(",", "", $session_percentage);
            $page_views = $Sheet->getCellByColumnAndRow(6, $j)->getValue();
            $page_views = str_replace(",", "", $page_views);
            $page_views_percentage = $Sheet->getCellByColumnAndRow(7, $j)->getValue();
            $page_views_percentage = str_replace(",", "", $page_views_percentage);
//            $quantity_ordered = $Sheet->getCellByColumnAndRow(8, $j)->getValue();
//            $goods_session_percentage = $Sheet->getCellByColumnAndRow(9, $j)->getValue();
//            $goods_session_percentage = (float)$goods_session_percentage / 100;
//            $quantity_sales = $Sheet->getCellByColumnAndRow(10, $j)->getValue();
//            $quantity_sales = str_replace(",", "", $quantity_sales);
//            $quantity_sales = substr($quantity_sales, 3);

            $skuSql = "select `id` from amazon_skulist where `sku`='$sku'";
            $checkSku = DB::select($skuSql);
            if ($checkSku == null) {
                $addSql = "insert into amazon_skulist(`shop_id`,`sku`,`father_asin`,`asin`,`time`) values ('$store','$sku','$father_asin','$son_asin','$time')";
                DB::insert($addSql);
            }
            if ($operation_id == 1) {
                $checksql = "SELECT
                    `id`,
                    `session`,
                    `session_percentage`,
                    `page_views`,
                    `page_views_percentage`              
                FROM
                    amazon_traffic
                WHERE
                    `sku` = '$sku'
                AND `date` = '$date'";
                $check = DB::select($checksql);
                if ($check == null) {
                    $sql = "INSERT INTO amazon_traffic (
                    `shop_id`,
                    `father_asin`,
                    `son_asin`,
                    `sku`,
                    `session`,
                    `session_percentage`,
                    `page_views`,
                    `page_views_percentage`,
                    `date`,
                    `time`
                )
                VALUES
                    (
                        '$store',
                        '$father_asin',
                        '$son_asin',
                        '$sku',
                        '$session',
                        '$session_percentage',
                        '$page_views',
                        '$page_views_percentage',
                        '$date',
                        '$time'
                    )";
                    $result = DB::insert($sql);

                    if (!$result) {
                        return [
                            'type' => 'fail',
                            'msg' => '导入失败，Excel文件错误'
                        ];
                    } else {
                        $a++;
                    }
                } else {
                    return [
                        'type' => 'fail',
                        'msg' => '导入失败，文件中包含已上传数据'
                    ];
                }
            } else {
                $checksql = "SELECT
                        `id`                       
                        FROM
                        amazon_traffic
                         WHERE
                        `sku` = '$sku'
                        AND `date` = '$date'";
                $check = DB::select($checksql);
                if (!empty($check)) {
                    $id = $check[0]->id;
                    $updatesql = "UPDATE amazon_traffic
                        SET `shop_id` = '$store',
                         `session` = $session,
                         `session_percentage` = '$session_percentage',
                         `page_views` = $page_views,
                         `page_views_percentage` = '$page_views_percentage',                                 
                         `time` = '$time'
                        WHERE
                            `id` = '$id'";
                    $result = DB::update($updatesql);
                    if ($result) $b++;
                } else {
                    return [
                        'type' => 'fail',
                        'msg' => '导入失败，请选择上传新数据'
                    ];
                }
            }

        }

        return [
            'type' => 'success',
            'msg' => '导入成功，本次共导入' . $a . '条数据,更新' . $b . '条数据'
        ];

    }

    /*
     * 亚马逊品类数据导入
     */
    public function amazon_category_excel($params)
    {

        $file = $params['file'];
        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();

        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }
        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }
        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);
        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        //循环插入流量数据
        $a = 0;
        $b = 0;
        $time = time();
        $categorySql = "select id,product_typename from amazon_category";
        $getcategory = DB::select($categorySql);
        $category = array();
        if (!empty($getcategory)) {
            foreach ($getcategory as $cateVal) {
                $category[$cateVal->product_typename] = $cateVal->id;
            }
        }
        $statuSql = "select id,category_status from amazon_category_status";
        $status = DB::select($statuSql);
        $categoryStatusMap = array();
        if (!empty($status)) {
            foreach ($status as $v) {
                $categoryStatusMap[$v->category_status] = $v->id;
            }
        }
        $userSql = "select id,account from users";
        $userData = DB::select($userSql);
        $userArr = array();
        if (!empty($userData)) {
            foreach ($userData as $userVal) {
                $userArr[$userVal->account] = $userVal->id;
            }
        }
        $insert = '';
        $update_shop_id = '';
        $update_spu = '';
        $update_user_id = '';
        $update_gender = '';
        $update_category_id = '';
        $update_sales_status = '';
        $update_custom_sku = '';
        $update_goods_style = '';
        $update_img = '';
        $update_time = '';
        $update_id = '';
        $update_code_id = '';
        $product_name_arr = '';
        $fnsku_str = '';
        $asin_str = '';

        for ($j = 3; $j <= $allRow; $j++) {

            $shop_id = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            $sku = $Sheet->getCellByColumnAndRow(1, $j)->getValue();
            if($sku==null) continue;
            $father_asin = '';
            $fnsku = '';
            $asin = '';
            $product_detail_data = Db::table('product_detail')
                ->select('fnsku', 'asin', 'parent_asin')
                ->where('sellersku', $sku)
                ->first();
            if (!empty($product_detail_data)) {
                $fnsku = $product_detail_data->fnsku;
                $asin = $product_detail_data->asin;
                $father_asin = $product_detail_data->parent_asin;
            }

            //中文名
            $product_name_data = Db::table('saihe_product_detail as spd')
                ->select('sp.product_name_cn', 'sp.client_sku','sp.small_image_url','sp.product_group_sku')
                ->leftJoin('saihe_product as sp', 'sp.sku', '=', 'spd.saihe_sku')
                ->where('spd.order_source_sku', $sku)
                ->get()
                ->toArray();
            $product_name = '';
            $client_sku = '';
            $client_img = '';
            $spu = '';
            if ($product_name_data) {
                if(isset($product_name_data[0]->product_name_cn)){
                    $product_name = strstr($product_name_data[0]->product_name_cn, $product_name_data[0]->client_sku);
                }
                if ($product_name === false) {
                    $product_name = $product_name_data[0]->product_name_cn;
                }
                $client_sku = $product_name_data[0]->client_sku;//库存sku
                $client_img = $product_name_data[0]->small_image_url;
                $spu = $product_name_data[0]->product_group_sku;
            }

            $sales_name = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());//销售状态
            $style = trim($Sheet->getCellByColumnAndRow(3, $j)->getValue());//款式
            $style_id = 0;
            if ($style == '四季款') {
                $style_id = 1;
            } elseif ($style == '夏季款') {
                $style_id = 2;
            } elseif ($style == '冬季款') {
                $style_id = 3;
            }
            $category_name = trim($Sheet->getCellByColumnAndRow(4, $j)->getValue());//品类名称
            $category_id = 0;
            if (!empty($category)) {
                if (array_key_exists($category_name, $category)) {
                    $category_id = $category[$category_name];
                } else {
                    $category_id = DB::table('amazon_category')->insertGetId(['product_typename' => $category_name]);
                    if ($category_id) $category[$category_name] = $category_id;
                }
            } else {
                $category_id = DB::table('amazon_category')->insertGetId(['product_typename' => $category_name]);
                if ($category_id) $category[$category_name] = $category_id;
            }
            $gender = $Sheet->getCellByColumnAndRow(5, $j)->getValue();//性别
            $user_name = $Sheet->getCellByColumnAndRow(6, $j)->getValue();//运营
            $user_id = 0;
            if (!empty($user_name)) {
                if (!empty($userArr)) {
                    if (isset($userArr[$user_name])) {
                        $user_id = $userArr[$user_name];
                    }
                }
            }
            $new_sku = '';
            $new_sku = $Sheet->getCellByColumnAndRow(7, $j)->getValue();//sku关联绑定sku
            $sales_status = 0;
            if (!empty($categoryStatusMap)) {
                if (isset($categoryStatusMap[$sales_name])) {
                    $sales_status = $categoryStatusMap[$sales_name];
                } else {
                    $sales_status = DB::table('amazon_category_status')->insertGetId(['category_status' => $sales_name]);
                    if ($sales_status) $categoryStatusMap[$sales_name] = $sales_status;
                }
            } else {
                $sales_status = DB::table('amazon_category_status')->insertGetId(['category_status' => $sales_name]);
                if ($sales_status) $categoryStatusMap[$sales_name] = $sales_status;
            }
            $check = DB::table('amazon_skulist')->where('sku',$sku)->select('id')->first();
            if (empty($check)) {
                $insert .= "('{$shop_id}','{$spu}','{$sku}','{$product_name}', '{$father_asin}','{$gender}','{$category_id}','{$sales_status}','{$user_id}','{$client_sku}','{$style_id}','{$client_img}','{$fnsku}','{$asin}','{$time}','{$new_sku}'),";
                $a++;
            } else {
                $id = $check->id;
                $update_shop_id .= "WHEN {$id} THEN '{$shop_id}'";
                $update_spu .= "WHEN {$id} THEN '{$spu}'";
                $update_sales_status .= "WHEN {$id} THEN '{$sales_status}' ";
                $update_user_id .= "WHEN {$id} THEN '{$user_id}' ";
                $update_gender .= "WHEN {$id} THEN '{$gender}' ";
                $product_name_arr .= "WHEN {$id} THEN '{$product_name}' ";
                $update_category_id .= "WHEN {$id} THEN '{$category_id}' ";
                $update_custom_sku .= "WHEN {$id} THEN '{$client_sku}' ";
                $update_goods_style .= "WHEN {$id} THEN '{$style_id}' ";
                $update_img .= "WHEN {$id} THEN '{$client_img}' ";
                $fnsku_str .= "WHEN {$id} THEN '{$fnsku}' ";
                $asin_str .= "WHEN {$id} THEN '{$asin}' ";
                $update_time .= "WHEN {$id} THEN '{$time}' ";
                $update_code_id .= "WHEN {$id} THEN '{$new_sku}'";
                ///$update_time .= "WHEN '{$list_v['style_no']}' THEN '{$time}' ";
                $update_id .= "'{$id}',";
                $b++;
            }

        }//die;

        //去除多余的逗号
        $new_insert = substr($insert, 0, strlen($insert) - 1);
        $new_id = substr($update_id, 0, strlen($update_id) - 1);
        if (!empty($new_insert)) {
            $insert_sql = "INSERT INTO amazon_skulist (
                        `shop_id`,
                        `spu`,
                        `sku`,
                        `product_name`,
                        `father_asin`,
                        `gender`,
                        `category_id`,
                        `sales_status`,
                        `user_id`,
                        `custom_sku`,
                        `goods_style`,
                        `img`,
                        `fnsku`,
                        `asin`,
                        `time`,
                        `new_sku`
                    )
                    VALUES
                       {$new_insert}";
            $insert_res = Db::insert($insert_sql);

        }

        if (!empty($new_id)) {
            $update_sql = "update amazon_skulist
                                                    set `shop_id` = Case id {$update_shop_id} END,
                                                        `spu` = Case id {$update_spu} END,
                                                        `sales_status` = Case id {$update_sales_status} END,
                                                        `user_id` = Case id {$update_user_id} END,
                                                        `gender` = Case id {$update_gender} END,
                                                        `product_name` = Case id {$product_name_arr} END,
                                                        `category_id` = Case id {$update_category_id} END,
                                                        `custom_sku` = Case id {$update_custom_sku} END,
                                                        `goods_style` = Case id {$update_goods_style} END,
                                                        `img` = Case id {$update_img} END,
                                                        `fnsku` = Case id {$fnsku_str} END,
                                                        `asin` = Case id {$asin_str} END,
                                                        `time` =  Case id {$update_time} END,
                                                        `new_sku` =  Case id {$update_code_id} END
                                                    where `id` in ({$new_id})";
//            var_dump($update_sql);die;
            $update = Db::update($update_sql);
        }

        return [
            'type' => 'success',
            'msg' => '导入成功，本次共导入' . $a . '条数据,更新' . $b . '条数据'
        ];

    }


    /*
     * 亚马逊在途库存数据导入
     */
    public function amazon_inroad_inventory_excel($params)
    {
        $file = $params['file'];
        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        $store = $params['store'];
        $date = $params['date'];
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }
        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }
        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);

        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        //循环插入流量数据
        $a = 0;
        $b = 0;
        $time = time();
        for ($j = 2; $j < $allRow; $j++) {
            $sku = $Sheet->getCellByColumnAndRow(0, $j)->getValue();
            $fnsku = $Sheet->getCellByColumnAndRow(1, $j)->getValue();
            $asin = $Sheet->getCellByColumnAndRow(2, $j)->getValue();
            $product_name = $Sheet->getCellByColumnAndRow(3, $j)->getValue();
            $product_name = str_replace("'", " ", $product_name);
            $inbound_working_quantity = $Sheet->getCellByColumnAndRow(15, $j)->getValue();
            $inbound_shipped_quantity = $Sheet->getCellByColumnAndRow(16, $j)->getValue();
            $inbound_receiving_quantity = $Sheet->getCellByColumnAndRow(17, $j)->getValue();

            $skuSql = "select id from amazon_skulist where `sku`='$sku'";
            $checkSku = DB::select($skuSql);
            if ($checkSku == null) {
                $addSql = "insert into amazon_skulist(`shop_id`,`sku`,`fnsku`,`asin`,`product_name`,`time`) values ('$store','$sku','$fnsku','$asin','$product_name','$time')";
                DB::insert($addSql);
            } else {
                $skuId = $checkSku[0]->id;
                $updateSql = "update amazon_skulist set `fnsku`='$fnsku',`product_name`='$product_name',`time`='$time' where `id`='$skuId'";
                DB::update($updateSql);
            }
            $tongan_inventory = '';//同安仓库存
            $tonganSql = "select a.good_num from saihe_inventory a left join saihe_product_detail b on a.sku=b.saihe_sku where b.asin='$asin' and a.warehouse_id=2 limit 1";
            $tongan = DB::select($tonganSql);
            if (!empty($tongan)) $tongan_inventory = $tongan[0]->good_num;
            $quantity_available = '';//在仓库存
            $zaicangSql = "select total_supply_quantity,instock_supply_quantity from product_detail where `sellersku`='$sku' and platform_id=5";
            $zaicang = DB::select($zaicangSql);
            if (!empty($zaicang)) $quantity_available = $zaicang[0]->total_supply_quantity + $zaicang[0]->instock_supply_quantity;
            $checksql = "select id from amazon_inventory where `shop_id`='{$store}' and `sku`='{$sku}' and `fnsku`='{$fnsku}' and `asin`='{$asin}' and `date`='{$date}'";
            $check = DB::select($checksql);
            if ($check == null) {
                $sql = "INSERT INTO amazon_inventory (
                        `shop_id`,
                        `sku`,
                        `fnsku`,
                        `asin`,
                        `inbound_working_quantity`,
                        `inbound_shipped_quantity`,
                        `inbound_receiving_quantity`,
                        `quantity_available`,
                        `tongan_inventory`,
                        `date`,
                        `time`
                    )
                    VALUES
                        (
                            '$store',
                            '$sku',
                            '$fnsku',
                            '$asin',
                            '$inbound_working_quantity',
                            '$inbound_shipped_quantity',
                            '$inbound_receiving_quantity',
                            '$quantity_available',
                            '$tongan_inventory',
                            '$date',
                            '$time'
                        )";
                DB::insert($sql);
                $a++;
            } else {
                $id = $check[0]->id;
                $updatesql = "UPDATE amazon_inventory
                    SET `inbound_working_quantity` = '$inbound_working_quantity',
                     `inbound_shipped_quantity` = '$inbound_shipped_quantity',
                     `inbound_receiving_quantity` = '$inbound_receiving_quantity',
                     `quantity_available` =  '$quantity_available',
                     `tongan_inventory` = '$tongan_inventory',
                     `time` = '$time'
                    WHERE
                        `id` = '$id'";
                DB::update($updatesql);
                $b++;
            }
        }

        return [
            'type' => 'success',
            'msg' => '导入成功，本次共导入' . $a . '条数据,更新' . $b . '条数据'
        ];

    }

    /*
     * 亚马逊预留库存数据导入
     */
    public function amazon_reserved_inventory_excel($params)
    {
        $file = $params['file'];
        $store = $params['store'];
        $date = $params['date'];
        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }
        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }
        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);

        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();

        //循环插入流量数据
        $a = 0;
        $b = 0;
        $time = time();
        for ($j = 2; $j < $allRow; $j++) {
            $sku = $Sheet->getCellByColumnAndRow(0, $j)->getValue();
            $fnsku = $Sheet->getCellByColumnAndRow(1, $j)->getValue();
            $asin = $Sheet->getCellByColumnAndRow(2, $j)->getValue();
            $product_name = $Sheet->getCellByColumnAndRow(3, $j)->getValue();
            $product_name = str_replace("'", " ", $product_name);
            $reserved_fc_transfers = $Sheet->getCellByColumnAndRow(6, $j)->getValue();
            $reserved_fc_processing = $Sheet->getCellByColumnAndRow(7, $j)->getValue();

            $skuSql = "select id from amazon_skulist where `sku`='$sku'";
            $checkSku = DB::select($skuSql);
            if ($checkSku == null) {
                $addSql = "INSERT INTO amazon_skulist (
                        `shop_id`,
                        `sku`,
                        `fnsku`,
                        `asin`,
                        `product_name`,
                        `time`
                    )
                    VALUES
                        (
                            '$store',
                            '$sku',
                            '$fnsku',
                            '$asin',
                            '$product_name',
                            '$time'
                        )";
                DB::insert($addSql);
            } else {
                $skuId = $checkSku[0]->id;
                $updateSql = "update amazon_skulist set `fnsku`='$fnsku',`product_name`='$product_name',`time`='$time' where `id`='$skuId'";
                DB::update($updateSql);
            }
            $tongan_inventory = '';//同安仓库存
            $tonganSql = "select a.good_num from saihe_inventory a left join saihe_product_detail b on a.sku=b.saihe_sku where b.asin='$asin' and a.warehouse_id=2 limit 1";
            $tongan = DB::select($tonganSql);
            if (!empty($tongan)) $tongan_inventory = $tongan[0]->good_num;
            $quantity_available = '';//在仓库存
            $zaicangSql = "select total_supply_quantity,instock_supply_quantity from product_detail where `sellersku`='$sku' and platform_id=5";
            $zaicang = DB::select($zaicangSql);
            if (!empty($zaicang)) $quantity_available = $zaicang[0]->total_supply_quantity + $zaicang[0]->instock_supply_quantity;
            $checksql = "select id from amazon_inventory where `shop_id`='{$store}' and `sku`='{$sku}' and `fnsku`='{$fnsku}' and `asin`='{$asin}' and `date`='{$date}'";
            $check = DB::select($checksql);
            if ($check == null) {
                $sql = "INSERT INTO amazon_inventory (
                    `shop_id`,
                    `sku`,
                    `fnsku`,
                    `asin`,
                    `reserved_fc_transfers`,
                    `reserved_fc_processing`,
                    `quantity_available`,                 
                    `tongan_inventory`,
                    `date`,
                    `time`
                )
                VALUES
                    (
                        '$store',
                        '$sku',
                        '$fnsku',
                        '$asin',
                        '$reserved_fc_transfers',
                        '$reserved_fc_processing',
                        '$quantity_available',
                        '$tongan_inventory',
                        '$date',
                        '$time'
                    )";
                DB::insert($sql);
                $a++;
            } else {
                $id = $check[0]->id;
                $updatesql = "UPDATE amazon_inventory
                    SET `reserved_fc_transfers` = '$reserved_fc_transfers',
                     `reserved_fc_processing` = '$reserved_fc_processing',
                     `quantity_available` =  '$quantity_available',
                     `tongan_inventory` = '$tongan_inventory',
                     `time` = '$time'
                    WHERE
                        `id` = '$id'";
                DB::update($updatesql);
                $b++;
            }
        }

        return [
            'type' => 'success',
            'msg' => '导入成功，本次共导入' . $a . '条数据,更新' . $b . '条数据'
        ];
    }


    /*
      *  shopee商品广告数据导入
      */

    public function shopee_adv_excel($params)
    {

        $file = $params['file'];
        $date = '';
        $shop_id = $params['store'];
        $start_date = $params['start_date'];
        $end_date = $params['end_date'];
        $shopData = Shop::where('id', $shop_id)->first();
        if (!isset($shopData['country_id'])) {
            return [
                'type' => 'fail',
                'msg' => '不支持csv格式'
            ];

        }
        if (!($shopData['country_id'] > 0)) {
            return [
                'type' => 'fail',
                'msg' => '店铺未设置国家'
            ];
        }
        $Countrys = Countrys::where('id', $shopData['country_id'])->first();
        if (!isset($Countrys['currency'])) {
            return [
                'type' => 'fail',
                'msg' => '对应国家的货币未设置'
            ];
        }
        $Huilv = Huilv::where('currency', $Countrys['currency'])->orderBy('id', 'desc')->first();
        if (!isset($Huilv['dollar_rate'])) {
            return [
                'type' => 'fail',
                'msg' => '货币汇率未设置'
            ];
        }


        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
//            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }
        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);

        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        $a = 0;
        $b = 0;
        $time = time();
        //循环插入流量数据
        for ($j = 8; $j <= $allRow; $j++) {
            $adv_name = $Sheet->getCellByColumnAndRow(1, $j)->getValue();
            $adv_name = str_replace("'", " ", $adv_name);
            $adv_status = $Sheet->getCellByColumnAndRow(2, $j)->getValue();
            $product_id = $Sheet->getCellByColumnAndRow(3, $j)->getValue();
            $product_id = trim($product_id);
            $adv_type = $Sheet->getCellByColumnAndRow(4, $j)->getValue();
            $keyword = $Sheet->getCellByColumnAndRow(5, $j)->getValue();
            $startdate = $Sheet->getCellByColumnAndRow(6, $j)->getValue();
            $enddate = $Sheet->getCellByColumnAndRow(7, $j)->getValue();
            $show_num = $Sheet->getCellByColumnAndRow(8, $j)->getValue();
            $click_num = $Sheet->getCellByColumnAndRow(9, $j)->getValue();
            $click_rate = $Sheet->getCellByColumnAndRow(10, $j)->getValue();
            $click_rate = sprintf("%01.2f", $click_rate * 100) . '%';
            $conversion = $Sheet->getCellByColumnAndRow(11, $j)->getValue();
            $is_conversion = $Sheet->getCellByColumnAndRow(12, $j)->getValue();
            $conversion_rate = $Sheet->getCellByColumnAndRow(13, $j)->getValue();
            $conversion_rate = sprintf("%01.2f", $conversion_rate * 100) . '%';
            $is_conversion_rate = $Sheet->getCellByColumnAndRow(14, $j)->getValue();
            $is_conversion_rate = sprintf("%01.2f", $is_conversion_rate * 100) . '%';
            $conversion_cost = $Sheet->getCellByColumnAndRow(15, $j)->getValue();
            $is_conversion_cost = $Sheet->getCellByColumnAndRow(16, $j)->getValue();
            $goods_sold = $Sheet->getCellByColumnAndRow(17, $j)->getValue();
            $is_goods_sold = $Sheet->getCellByColumnAndRow(18, $j)->getValue();
            $sales_amount = $Sheet->getCellByColumnAndRow(19, $j)->getValue();
            $is_sales_amount = $Sheet->getCellByColumnAndRow(20, $j)->getValue();
            $cost = $Sheet->getCellByColumnAndRow(21, $j)->getValue();
            $investment_output_ratio = $Sheet->getCellByColumnAndRow(22, $j)->getValue();
            $is_investment_output_ratio = $Sheet->getCellByColumnAndRow(23, $j)->getValue();
            $cost_income_comparison = $Sheet->getCellByColumnAndRow(24, $j)->getValue();
            $is_cost_income_comparison = $Sheet->getCellByColumnAndRow(25, $j)->getValue();
            $is_cost_income_comparison = sprintf("%01.2f", $is_cost_income_comparison * 100) . '%';

            $conversion_cost_us = round(($conversion_cost * $Huilv['dollar_rate']), 2);
            $is_conversion_cost_us = round(($is_conversion_cost * $Huilv['dollar_rate']), 2);
            $sales_amount_us = round(($sales_amount * $Huilv['dollar_rate']), 2);
            $is_sales_amount_us = round(($is_sales_amount * $Huilv['dollar_rate']), 2);
            $cost_us = round(($cost * $Huilv['dollar_rate']), 2);
            $huilv_id = $Huilv['id'];


//            $checksql = "select id from shopee_adv where `product_id`='$product_id' and `keyword`='$keyword' and `date`='$date'";
            $checksql = "select id from shopee_adv where `shop_id`={$shop_id} and `product_id`='$product_id' and `keyword`='$keyword' and `start_date`='$start_date' and `end_date` = '$end_date'";
            $check = DB::select($checksql);
            if ($check == null) {
                $sql = "insert into shopee_adv(`shop_id`,`adv_name`,`adv_status`,`product_id`,`adv_type`,`keyword`,`startdate`
,`enddate`,`show_num`,`click_num`,`click_rate`,`conversion`,`is_conversion`,`conversion_rate`
,`is_conversion_rate`,`conversion_cost`,`is_conversion_cost`,`goods_sold`,`is_goods_sold`,`sales_amount`
,`is_sales_amount`,`cost`,`investment_output_ratio`,`is_investment_output_ratio`,`cost_income_comparison`
,`is_cost_income_comparison`,`date`,`time`
,`conversion_cost_us`,`is_conversion_cost_us`,`sales_amount_us`,`is_sales_amount_us`,`cost_us`,`huilv_id`,`start_date`,`end_date`) 
values ('$shop_id','$adv_name','$adv_status','$product_id','$adv_type','$keyword','$startdate','$enddate','$show_num',
        '$click_num','$click_rate','$conversion','$is_conversion','$conversion_rate','$is_conversion_rate',
        '$conversion_cost','$is_conversion_cost','$goods_sold','$is_goods_sold','$sales_amount','$is_sales_amount',
        '$cost','$investment_output_ratio','$is_investment_output_ratio','$cost_income_comparison','$is_cost_income_comparison','$date'
        ,'$time','$conversion_cost_us','$is_conversion_cost_us','$sales_amount_us','$is_sales_amount_us','$cost_us','$huilv_id','$start_date','$end_date')";

                DB::insert($sql);
                $a++;
            } else {
                $id = $check[0]->id;
                $updatesql = "update shopee_adv set `shop_id`='$shop_id',`adv_name`='$adv_name',`adv_status`='$adv_status',
                      `adv_type`='$adv_type',`startdate`='$startdate',`enddate`='$enddate',`show_num`='$show_num',
                      `click_num`='$click_num',`click_rate`='$click_rate',`conversion`='$conversion',
                      `is_conversion`='$is_conversion',`conversion_rate`='$conversion_rate',
                      `is_conversion_rate`='$is_conversion_rate',`conversion_cost`='$conversion_cost',
                      `is_conversion_cost`='$is_conversion_cost',`goods_sold`='$goods_sold',
                      `is_goods_sold`='$is_goods_sold',`sales_amount`='$sales_amount',`is_sales_amount`='$is_sales_amount',
                      `cost`='$cost',`investment_output_ratio`='$investment_output_ratio',
                      `is_investment_output_ratio`='$is_investment_output_ratio',
                      `cost_income_comparison`='$cost_income_comparison',
                      `is_cost_income_comparison`='$is_cost_income_comparison',
                      `time`='$time',`start_date`='$start_date',`end_date`='$end_date'
where `id`='$id'";

                DB::update($updatesql);
                $b++;
            }

        }

        return [
            'type' => 'success',
            'msg' => '导入成功，本次共导入' . $a . '条数据,更新' . $b . '条数据'
        ];


    }



     /*
    *  亚马逊补货excel导入
    */

    public function replenish_ExcelImport($params)
    {
        $file = $params['file'];
        $token = $params['token'];

        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }
        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }
        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);

        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();

        $allRow = $allRow + 1;
        //循环插入流量数据
        $i = 0;
        for ($j = 2; $j < $allRow; $j++) {
            $shop_data_id = $Sheet->getCellByColumnAndRow(0, $j)->getValue();
//            $user_name = $Sheet->getCellByColumnAndRow(1, $j)->getValue();
            $sku = $Sheet->getCellByColumnAndRow(1, $j)->getValue();
            if($sku==null) continue;
            if(!is_string($sku)){
                return [
                    'type' => 'fail',
                    'msg' => '导入失败，第'.$j.'行,sku格式错误'
                ];
            }

//            $res['user_name'] = $user_name;
            $res['shop_id'] = $shop_data_id; 
            $res['sku'] = $sku;
            $res['request_num'] = $Sheet->getCellByColumnAndRow(2, $j)->getValue() ?? 0;
            $oldSku = $this->GetOldSku($sku);
            if($oldSku){
                $sku = $oldSku;
            }
            $sku_id = $this->GetSkuId($sku);
            $sku_list = Db::table('product_detail')->where('sku_id',$sku_id )->select('fnsku','title')->first();
//            $sku_list = Db::table('self_sku as a')->leftJoin('product_detail as b','a.id','=','b.sku_id')->where('a.sku', $sku)->orWhere('a.old_sku', $sku)->select('b.fnsku','a.shop_id','b.title')->first();

            if (!$sku_list) {
                return [
                    'type' => 'error',
                    'msg' => '此sku无fnsku,等待采集或补货预警列表手动刷新后重试'.$sku
                ];
            }
            if (empty($sku_list->fnsku)) {
                return [
                    'type' => 'error',
                    'msg' => '未获取到'.$sku.'的fnsku,无法补货'
                ];
            }
            if (empty($sku_list->title)) {
                return [
                    'type' => 'error',
                    'msg' => '未获取到'.$sku.'的英文名,无法补货'
                ];
            }

            // if (empty($sku_list->shop_id)) {
            //     return [
            //         'type' => 'error',
            //         'msg' => '未获取到'.$sku.'的店铺id,无法补货'
            //     ];
            // }
            // $shop_id = $sku_list->shop_id;


            if (!empty($sku)) {
                $return[$i] = $res;
                $i++;
            }

        }

        $returns =  [
            'type' => 'success',
            'msg' =>  $return
        ];
        return [
            'type' => 'success',
            'msg' => $returns
        ];

    }



    /*
    *  亚马逊补货excel导入
    */

//    public function replenish_ExcelImport_b($params)
//    {
//        $file = $params['file'];
//        $token = $params['token'];
//        //根据token识别申请人
//        $user_data = DB::table('users')->where('token', '=', $token)->select('Id', 'account')->get();
//        $user_name = $user_data[0]->account;
//        $user_id = $user_data[0]->Id;
//        //获取文件后缀名
//        $extension = $file->getClientOriginalExtension();
//        if ($extension == 'csv') {
//            $PHPExcel = new \PHPExcel_Reader_CSV();
//        } elseif ($extension == 'xlsx') {
//            $PHPExcel = new \PHPExcel_Reader_Excel2007();
//        } else {
//            $PHPExcel = new \PHPExcel_Reader_Excel5();
//        }
//        if (!$PHPExcel->canRead($file)) {
//            return [
//                'type' => 'fail',
//                'msg' => '导入失败，Excel文件错误'
//            ];
//        }
//        $PHPExcelLoad = $PHPExcel->load($file);
//        $Sheet = $PHPExcelLoad->getSheet(0);
//
//        /**取得一共有多少行*/
//        $allRow = $Sheet->getHighestRow();
//
//        $allRow = $allRow + 1;
//        //循环插入流量数据
//        $i = 0;
//        $find_sku = '';
//        for ($j = 2; $j < $allRow; $j++) {
//            $shop_id = '';
//            $user_id = '';
//            $shop_data_id = $Sheet->getCellByColumnAndRow(0, $j)->getValue();
//            $user_name = $Sheet->getCellByColumnAndRow(1, $j)->getValue();
//            $sku = $Sheet->getCellByColumnAndRow(2, $j)->getValue();
//            if($sku==null) continue;
//            if(!is_string($sku)){
//                return [
//                    'type' => 'fail',
//                    'msg' => '导入失败，第'.$j.'行,sku格式错误'
//                ];
//            }
//            $res['user_id'] = $user_id;
//            $res['user_name'] = $user_name;
//            $res['sku'] = $sku;
//            $res['courier_num'] = $Sheet->getCellByColumnAndRow(3, $j)->getValue() ?? 0;
//            $courier_num_next = $Sheet->getCellByColumnAndRow(3, $j + 1)->getValue() ?? 0;
//            $res['shipping_num'] = $Sheet->getCellByColumnAndRow(4, $j)->getValue() ?? 0;
//            $shipping_num_next = $Sheet->getCellByColumnAndRow(4, $j + 1)->getValue() ?? 0;
//            $res['air_num'] = $Sheet->getCellByColumnAndRow(5, $j)->getValue() ?? 0;
//            $air_num_next = $Sheet->getCellByColumnAndRow(5, $j + 1)->getValue() ?? 0;
//            if (($res['courier_num'] > 0 && ($res['shipping_num'] > 0 || $res['air_num'] > 0)) || ($res['courier_num'] > 0 && ($shipping_num_next > 0 || $air_num_next > 0))) {
//                return [
//                    'type' => 'error',
//                    'msg' => '导入失败，请填写同一种运输方式'
//                ];
//            } elseif (($res['shipping_num'] > 0 && ($res['courier_num'] > 0 || $res['air_num'] > 0)) || ($res['shipping_num'] > 0 && ($courier_num_next > 0 || $air_num_next > 0))) {
//                return [
//                    'type' => 'error',
//                    'msg' => '导入失败，请填写同一种运输方式'
//                ];
//            } elseif (($res['air_num'] > 0 && ($res['courier_num'] > 0 || $res['shipping_num'] > 0)) || ($res['air_num'] > 0 && ($courier_num_next > 0 || $shipping_num_next > 0))) {
//                return [
//                    'type' => 'error',
//                    'msg' => '导入失败，请填写同一种运输方式'
//                ];
//            }
////            $shopres = DB::select("SELECT shop_id from amazon_traffic where sku='$sku'");
//            $sku_list = Db::table('self_sku')->where('sku', $sku)->orWhere('old_sku', $sku)->get()->toArray();
////            foreach ($shopres as $shopvalue) {
//            if ($sku_list) {
//                $shop_id = $sku_list[0]->shop_id;
//                if ($shop_id != $shop_data_id) {
//                    return [
//                        'type' => 'error',
//                        'msg' => "{$sku}的店铺id错误"
//                    ];
//                }
//            }
//
////            }
//
//            if (!$sku_list) {
//
//                $product_detail_data = Db::table('product_detail')
//                    ->select('small_image', 'fnsku', 'asin', 'parent_asin')
//                    ->where('sellersku', $sku)
//                    ->first();
//                if (!$product_detail_data) {
//                    return [
//                        'type' => 'error',
//                        'msg' => '导入失败，该SKU暂未收录' . $sku
//                    ];
//                } else {
//                    $client_img = $product_detail_data->small_image;
//                    $fnsku = $product_detail_data->fnsku;
//                    $asin = $product_detail_data->asin;
//                    $father_asin = $product_detail_data->parent_asin;
//                }
//
//                $client_sku = '';
//                $clientSql = "SELECT
//                                a.client_sku,a.small_image_url
//                            FROM
//                                saihe_product a
//                            LEFT JOIN saihe_product_detail b ON a.sku = b.saihe_sku
//                            WHERE  b.order_source_sku = '$sku'
//                            ";
//                $client = DB::select($clientSql);
//
//                if (!empty($client)) {
//                    $client_sku = $client[0]->client_sku;//库存sku
//                }
//
//                $user = Db::table('users')->where('account', $user_name)->pluck('Id');
//                if (isset($user[0])) {
//                    $user_id = $user[0];
//                }
//
//                $product_name_data = Db::table('saihe_product_detail as spd')
//                    ->select('sp.product_name_cn', 'sp.client_sku')
//                    ->leftJoin('saihe_product as sp', 'sp.sku', '=', 'spd.saihe_sku')
//                    ->where('spd.order_source_sku', $sku)
//                    ->get()
//                    ->toArray();
//                $product_name = '';
//                if (isset($product_name_data[0])) {
//                    if(isset($product_name_data[0]->product_name_cn)){
//                        $product_name = strstr($product_name_data[0]->product_name_cn, $product_name_data[0]->client_sku);
//                    }
//                    if ($product_name === false) {
//                        $product_name = $product_name_data[0]->product_name_cn;
//                    }
//                }
//                $sku_data['fnsku'] = $fnsku;
//                $sku_data['asin'] = $asin;
//                $sku_data['father_asin'] = $father_asin;
//                $sku_data['shop_id'] = $shop_data_id;
//                $sku_data['sku'] = $sku;
//                $sku_data['custom_sku'] = $client_sku;
//                $sku_data['img'] = $client_img;
//                $sku_data['product_name'] = $product_name;
//                $sku_data['user_id'] = $user_id;
//                $return['find'][$i] = $sku_data;
//                // $insert = Db::table('amazon_skulist')->insert($sku_data);
//            }
//            $res['shop_id'] = $shop_id ?? 0;
//            $inventorySql = "SELECT a.good_num FROM saihe_inventory a LEFT JOIN saihe_product_detail b ON a.sku = b.saihe_sku WHERE  b.order_source_sku = '$sku' AND a.warehouse_id in (2,386) ";
//            $tongAn_inventory = 0;
//            $inventory = DB::select($inventorySql);
//            if (!empty($inventory)) {
//                foreach ($inventory as $inventoryVal) {
//                    $tongAn_inventory += $inventoryVal->good_num;
//                }
//            }
//            $res['tongAn_inventory'] = $tongAn_inventory;
//            // $is_success = $this->excel_create_buhuoDoc($res);
//            // if ($is_success == 0) {
//            //     $res['air_num'] = 0;
//            //     $res['courier_num'] = 0;
//            //     $res['shipping_num'] = 0;
//            // }
//            if (!empty($sku)) {
//                $return['data'][$i] = $res;
//                $i++;
//            }
//
//        }
//
//
//        if (isset($return['find']) && !empty($return['find'])) {
//            $find_sku = implode(',', array_column($return['find'], 'sku'));
//            $return['find_msg'] = $find_sku . '未匹配到，是否继续补货';
//            return [
//                'type' => 'attention',
//                'msg' => $return
//            ];
//        }
//
//        $return_list['data'] = $return;
//        $return = $this->replenish_ExcelImport_confirm($return_list);
//        return [
//            'type' => 'success',
//            'msg' => $return
//        ];
//
//    }

    public function replenish_ExcelImport_confirm($params)
    {
        $data = $params['data'];
        if (isset($data['find']) && !empty($data['find'])) {
            foreach ($data['find'] as $key => $value) {
                $insert = Db::table('amazon_skulist')->insert($value);
            }
        }

        return [
            'type' => 'success',
            'msg' => $data['data']
        ];
    }

    /*
    *  shopee商品链接数据导入
    */

    public function shopee_link_excel($params)
    {
        $file = $params['file'];
        $date = '';
        $start_date = $params['start_date'];
        $end_date = $params['end_date'];
        $shop_id = $params['store'];

        $shopData = Shop::where('id', $shop_id)->first();
        if (!isset($shopData['country_id'])) {
            return [
                'type' => 'fail',
                'msg' => '找不到对应店铺'
            ];

        }
        if (!($shopData['country_id'] > 0)) {
            return [
                'type' => 'fail',
                'msg' => '店铺未设置国家'
            ];
        }
        $Countrys = Countrys::where('id', $shopData['country_id'])->first();
        if (!isset($Countrys['currency'])) {
            return [
                'type' => 'fail',
                'msg' => '对应国家的货币未设置'
            ];
        }
        $Huilv = Huilv::where('currency', $Countrys['currency'])->orderBy('id', 'desc')->first();
        if (!isset($Huilv['dollar_rate'])) {
            return [
                'type' => 'fail',
                'msg' => '货币汇率未设置'
            ];
        }


        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            return [
                'type' => 'fail',
                'msg' => '不支持csv格式'
            ];
//            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }
        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);

        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        $a = 0;
        $b = 0;
        $time = time();
        //循环插入流量数据
        for ($j = 2; $j < $allRow; $j++) {

            $goods_name = $Sheet->getCellByColumnAndRow(0, $j)->getValue();
            $goods_name = str_replace("'", " ", $goods_name);
            $goods_id = $Sheet->getCellByColumnAndRow(1, $j)->getValue();
            $goods_view = $Sheet->getCellByColumnAndRow(2, $j)->getValue();
            $goods_page_view = $Sheet->getCellByColumnAndRow(3, $j)->getValue();
            $goods_bounce_rate = $Sheet->getCellByColumnAndRow(4, $j)->getValue();
            $goods_bounce_rate = sprintf("%01.2f", $goods_bounce_rate * 100) . '%';
            $goods_like = $Sheet->getCellByColumnAndRow(5, $j)->getValue();
            $goods_visitors = $Sheet->getCellByColumnAndRow(6, $j)->getValue();
            $shopcart_quantity = $Sheet->getCellByColumnAndRow(7, $j)->getValue();
            $shopcart_rate = $Sheet->getCellByColumnAndRow(8, $j)->getValue();
            $shopcart_rate = sprintf("%01.2f", $shopcart_rate * 100) . '%';
            $buyers_ordered = $Sheet->getCellByColumnAndRow(9, $j)->getValue();
            $pieces_ordered = $Sheet->getCellByColumnAndRow(10, $j)->getValue();
            $ordered_sales = $Sheet->getCellByColumnAndRow(11, $j)->getValue();
            $visit_order_rate = $Sheet->getCellByColumnAndRow(12, $j)->getValue();
            $visit_order_rate = sprintf("%01.2f", $visit_order_rate * 100) . '%';
            $buyers_confirmed_order = $Sheet->getCellByColumnAndRow(13, $j)->getValue();
            $pieces_confirmed_order = $Sheet->getCellByColumnAndRow(14, $j)->getValue();
            $confirmed_order_sales = $Sheet->getCellByColumnAndRow(15, $j)->getValue();
            $access_confirm_rate = $Sheet->getCellByColumnAndRow(16, $j)->getValue();
            $access_confirm_rate = sprintf("%01.2f", $access_confirm_rate * 100) . '%';
            $determined_rate = $Sheet->getCellByColumnAndRow(17, $j)->getValue();
            $determined_rate = sprintf("%01.2f", $determined_rate * 100) . '%';
            $buyers_has_pay = $Sheet->getCellByColumnAndRow(18, $j)->getValue();
            $pieces_has_pay = $Sheet->getCellByColumnAndRow(19, $j)->getValue();
            $has_pay_sales = $Sheet->getCellByColumnAndRow(20, $j)->getValue();
            $access_pay_rate = $Sheet->getCellByColumnAndRow(21, $j)->getValue();
            $access_pay_rate = sprintf("%01.2f", $access_pay_rate * 100) . '%';

            $has_pay_sales_us = round(((float)$has_pay_sales * $Huilv['dollar_rate']), 2);
            $ordered_sales_us = round(((float)$ordered_sales * $Huilv['dollar_rate']), 2);
            $confirmed_order_sales_us = round(((float)$confirmed_order_sales * $Huilv['dollar_rate']), 2);

//            $checksql = "select id from shopee_link where `goods_id`='$goods_id' and `date`='$date'";
            $checksql = "select id from shopee_link where `shop_id`={$shop_id} and `goods_id`='$goods_id' and `start_date`='$start_date' and `end_date` = '$end_date'";
            $check = DB::select($checksql);
            if ($check == null) {
                $sql = "insert into shopee_link(`shop_id`,`goods_name`,`goods_id`,`goods_view`,`goods_page_view`,`goods_bounce_rate`
,`goods_like`,`goods_visitors`,`shopcart_quantity`,`shopcart_rate`,`buyers_ordered`,`pieces_ordered`,`ordered_sales`
,`visit_order_rate`,`buyers_confirmed_order`,`pieces_confirmed_order`,`confirmed_order_sales`,`access_confirm_rate`
,`determined_rate`,`buyers_has_pay`,`pieces_has_pay`,`has_pay_sales`,`access_pay_rate`,`date`,`time`,`has_pay_sales_us`
,`ordered_sales_us`,`confirmed_order_sales_us`,`start_date`,`end_date`) values ('$shop_id','$goods_name','$goods_id','$goods_view','$goods_page_view'
,'$goods_bounce_rate','$goods_like','$goods_visitors','$shopcart_quantity','$shopcart_rate','$buyers_ordered','$pieces_ordered'
,'$ordered_sales','$visit_order_rate','$buyers_confirmed_order','$pieces_confirmed_order','$confirmed_order_sales','$access_confirm_rate'
,'$determined_rate','$buyers_has_pay','$pieces_has_pay','$has_pay_sales','$access_pay_rate','$date','$time',
'$has_pay_sales_us','$ordered_sales_us','$confirmed_order_sales_us','$start_date','$end_date')";
                // echo $sql;
                DB::insert($sql);
                $a++;
            } else {
                $id = $check[0]->id;
                $updatesql = "update shopee_link set `shop_id`='$shop_id',`goods_name`='$goods_name',`goods_view`='$goods_view',
                       `goods_page_view`='$goods_page_view',`goods_bounce_rate`='$goods_bounce_rate',`goods_like`='$goods_like',
                       `goods_visitors`='$goods_visitors',`shopcart_quantity`='$shopcart_quantity',`shopcart_rate`='$shopcart_rate',
                       `buyers_ordered`='$buyers_ordered',`pieces_ordered`='$pieces_ordered',`ordered_sales`='$ordered_sales',
                       `visit_order_rate`='$visit_order_rate',`buyers_confirmed_order`='$buyers_confirmed_order',
                       `pieces_confirmed_order`='$pieces_confirmed_order',`confirmed_order_sales`='$confirmed_order_sales',
                       `access_confirm_rate`='$access_confirm_rate',`determined_rate`='$determined_rate',
                       `buyers_has_pay`='$buyers_has_pay',`pieces_has_pay`='$pieces_has_pay',
                       `has_pay_sales`='$has_pay_sales',`access_pay_rate`='$access_pay_rate',
                       `start_date`='$start_date',`end_date`='$end_date',
                       `time`='$time' where `id`='$id'";
//                var_dump($updatesql);die;
                DB::update($updatesql);
                $b++;
            }

        }

        return [
            'type' => 'success',
            'msg' => '导入成功，本次共导入' . $a . '条数据,更新' . $b . '条数据'
        ];

    }

    /**
     * 亚马逊导入查找spu
     * @param $params
     * @return string[]
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public function amazon_spu_excel($params)
    {
        set_time_limit(0);
        $file = $params['file'];

        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            return [
                'type' => 'fail',
                'msg' => '不支持csv格式'
            ];
//            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }
        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }
        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);

        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        $a = 0;
        $b = 0;
        $time = time();
        $list = array();
        for ($j = 2; $j < $allRow; $j++) {
            //取出sku和spu组成数组放入list中
            $listArr['sku'] = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            $listArr['spu'] = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
            $list[] = $listArr;
            $a++;
        }

        if (!$list) {
            return [
                'type' => 'fail',
                'msg' => 'excel数据为空'
            ];
        }
        //取出list中的sku
        $sku = array_filter(array_column($list, 'sku'));
        //查询amazon_skulist表中custom_sku字段和$sku相同的数据
        $amazonSkuList = AmazonSkulist::whereIn('custom_sku', $sku)->select('id', 'custom_sku')->get()->toarray();
        $updateSpu = '';
        $id = '';
        foreach ($amazonSkuList as $k => $v) {
            foreach ($list as $key => $value) {
                //判断两个数组中sku和custom_sku相同的数据
                if ($value['sku'] == $v['custom_sku']) {
                    $updateSpu .= "WHEN '{$v['id']}' THEN '{$value['spu']}' ";
                    $id .= "{$v['id']},";
                    $b++;
                }
            }
        }
        //去除多余的逗号
        $new_id = substr($id, 0, strlen($id) - 1);
        $update_sql = "update amazon_skulist
                                                    set `spu` = Case id {$updateSpu} END
                                                    where `id` in ({$new_id})";

        $update = Db::update($update_sql);
        if ($update === false) {
            return [
                'type' => 'fail',
                'msg' => '导入失败'
            ];
        }

        return [
            'type' => 'success',
            'msg' => '导入成功，本次共导入' . $a . '条数据,更新' . $b . '条数据'
        ];

    }


    //亚马逊品类数据导出
    public function amazon_categoryExport($params)
    {
        $data_type = isset($params['select_type']) ? $params['select_type'] : null;
        $where = "1=1";
        if (isset($params['category_id'])) {
            $category_id = $params['category_id'];
            if (!empty($category_id)) $where .= " and a.category_id in ($category_id)";
        }
        if (!empty($params['store'])) {
            $where .= " and a.shop_id = {$params['store']}";
        }
        if (!empty($params['sale_status'])) {
            $where .= " and a.sales_status = {$params['sale_status']}";
        }
        if (!empty($params['sku'])) {
            if (strstr($params['sku'], '，')) {
                $symbol = '，';
            } elseif (strstr($params['sku'], ',')) {
                $symbol = ',';
            } else {
                $symbol = '';
            }
            if ($symbol) {
                $skuarray = explode($symbol,$params['sku']);
                foreach ($skuarray as $key => $sku) {
                    if($key==0){
                        $where .= " and a.sku like '%{$sku}%' ";
                    }else{
                        $where .= " or a.sku like '%{$sku}%' ";
                    }
                }
            }else {
                $where .= " and a.sku like '%{$params['sku']}%' ";
            }
        }

        if (!empty($params['asin'])) {
            if (strstr($params['asin'], '，')) {
                $symbol = '，';
            } elseif (strstr($params['asin'], ',')) {
                $symbol = ',';
            } else {
                $symbol = '';
            }
            if ($symbol) {
                $asinarray = explode($symbol,$params['asin']);
                foreach ($asinarray as $key => $sku) {
                    if($key==0){
                        $where .= " and a.asin like '%{$sku}%' ";
                    }else{
                        $where .= " or a.asin like '%{$sku}%' ";
                    }
                }
            }else {
                $where .= " and a.asin like '%{$params['asin']}%' ";
            }

        }


        if (!empty($params['custom_sku'])) {
            if (strstr($params['custom_sku'], '，')) {
                $symbol = '，';
            } elseif (strstr($params['custom_sku'], ',')) {
                $symbol = ',';
            } else {
                $symbol = '';
            }
            if ($symbol) {
                $custom_skuarray = explode($symbol,$params['custom_sku']);
                foreach ($custom_skuarray as $key => $sku) {
                    if($key==0){
                        $where .= " and a.custom_sku like '%{$sku}%' ";
                    }else{
                        $where .= " or a.custom_sku like '%{$sku}%' ";
                    }
                }
            }else {
                $where .= " and a.custom_sku like '%{$params['custom_sku']}%' ";
            }
        }

        if (!empty($params['father_asin'])) {
            if (strstr($params['father_asin'], '，')) {
                $symbol = '，';
            } elseif (strstr($params['father_asin'], ',')) {
                $symbol = ',';
            } else {
                $symbol = '';
            }
            if ($symbol) {
                $father_asinarray = explode($symbol,$params['father_asin']);
                foreach ($father_asinarray as $key => $sku) {
                    if($key==0){
                        $where .= " and a.father_asin like '%{$sku}%' ";
                    }else{
                        $where .= " or a.father_asin like '%{$sku}%' ";
                    }
                }
            }else {
                $where .= " and a.father_asin like '%{$params['father_asin']}%' ";
            }
        }


        if (!empty($params['spu'])) {
            if (strstr($params['spu'], '，')) {
                $symbol = '，';
            } elseif (strstr($params['spu'], ',')) {
                $symbol = ',';
            } else {
                $symbol = '';
            }
            if ($symbol) {
                $spuarray = explode($symbol,$params['spu']);
                foreach ($spuarray as $key => $sku) {
                    if($key==0){
                        $where .= " and a.spu like '%{$sku}%' ";
                    }else{
                        $where .= " or a.spu like '%{$sku}%' ";
                    }
                }
            } else {
                $where .= " and a.spu like '%{$params['spu']}%' ";
            }
        }
        if (!empty($params['user_id'])) {
            $where .= " and a.user_id = {$params['user_id']} ";
        }
        if (!empty($params['style_id'])) {
            $where .= " and a.goods_style = {$params['style_id']} ";
        }
        if ($data_type == '0') {
            $where .= " and (a.category_id=0 or a.gender='' or a.user_id=0 or a.goods_style=0 or a.sales_status=0)";
        }
        if ($data_type == '1') {
            $where .= " and a.category_id!=0 and a.gender!='' and a.user_id!=0 and a.goods_style!=0 and a.sales_status!=0";
        }

        $fileName = "亚马逊品类数据" . date('Y-m-d');
        $fileType = 'xlsx';
        $sql = "SELECT
                a.sku,
                a.custom_sku,
                a.spu,
                a.father_asin,
                b.product_typename,
                c.category_status,
                a.gender,
                a.sales_status,
                u.account,
                s.shop_name,
                a.goods_style
            FROM
                amazon_skulist a
            LEFT JOIN amazon_category b ON a.category_id = b.id
            LEFT JOIN amazon_category_status c ON a.sales_status = c.id
            LEFT JOIN users u ON a.user_id = u.Id        
            LEFT JOIN shop s ON a.shop_id = s.Id
            WHERE
                $where
            ORDER BY
                a.id DESC";
        $data = json_decode(json_encode(DB::select($sql)), true);
        $obj = new \PHPExcel();

        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('亚马逊商品品类信息'); //设置标题

        // 设置当前sheet
        $obj->setActiveSheetIndex(0);

        // 设置当前sheet的名称
        $obj->getActiveSheet()->setTitle('亚马逊商品品类信息');

        // 列标
        $list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I','J'];

        // 填充第一行数据
        $obj->getActiveSheet()
            ->setCellValue($list[0] . '3', '店铺')
            ->setCellValue($list[1] . '3', 'sku')
            ->setCellValue($list[2] . '3', '销售状态')
            ->setCellValue($list[3] . '3', '款式')
            ->setCellValue($list[4] . '3', '品类')
            ->setCellValue($list[5] . '3', '性别')
            ->setCellValue($list[6] . '3', '运营')
            ->setCellValue($list[7] . '3', '库存sku')
            ->setCellValue($list[8] . '3', 'spu')
            ->setCellValue($list[9] . '3', 'father_asin');


        // 填充第n(n>=2, n∈N*)行数据
        $length = count($data);
        for ($i = 0; $i < $length; $i++) {
            $obj->getActiveSheet()->setCellValue($list[0] . ($i + 4), $data[$i]['shop_name'], \PHPExcel_Cell_DataType::TYPE_STRING);//将其设置为文本格式
            $obj->getActiveSheet()->setCellValue($list[1] . ($i + 4), $data[$i]['sku'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[2] . ($i + 4), $data[$i]['category_status'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $style = null;
            if ($data[$i]['goods_style'] == 1) {
                $style = '四季款';
            } elseif ($data[$i]['goods_style'] == 2) {
                $style = '夏季款';
            } elseif ($data[$i]['goods_style'] == 3) {
                $style = '冬季款';
            }
            $obj->getActiveSheet()->setCellValue($list[3] . ($i + 4), $style, \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[4] . ($i + 4), $data[$i]['product_typename'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[5] . ($i + 4), $data[$i]['gender'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[6] . ($i + 4), $data[$i]['account'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[7] . ($i + 4), $data[$i]['custom_sku'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[8] . ($i + 4), $data[$i]['spu'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[9] . ($i + 4), $data[$i]['father_asin'], \PHPExcel_Cell_DataType::TYPE_STRING);
        }

        // 设置加粗和左对齐
        foreach ($list as $col) {
            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($col . '1')->getFont()->setBold(true);
            // 设置第1-n行，左对齐
            for ($i = 1; $i <= $length + 1; $i++) {
                $obj->getActiveSheet()->getStyle($col . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            }
        }

        // 设置列宽
        $obj->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('B')->setWidth(30);
        $obj->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('J')->setWidth(20);

        // 导出
        ob_clean();
        if ($fileType == 'xls') {
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xls');
            header('Cache-Control: max-age=1');
            $objWriter = new \PHPExcel_Writer_Excel5($obj);
            $objWriter->save('php://output');
            exit;
        } elseif ($fileType == 'xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');
            header('Cache-Control: max-age=1');
            $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
            $objWriter->save('php://output');
            exit;
        }
    }

    //亚马逊补货预警导出
    public function amazon_warnExport($params)
    {
        $path = "./admin/export/";
        $this->deleteFile($path);
        $fileName = "亚马逊补货预警数据" . date('Y-m-d');
        $fileType = 'xlsx';
        $data = json_decode($params['data'], true);
        $thisDate = $params['thisDate'];
        $beforeDate = $params['beforeDate'];
        $obj = new \PHPExcel();
        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('亚马逊补货预警信息'); //设置标题

        // 设置当前sheet
        $obj->setActiveSheetIndex(0);

        // 设置当前sheet的名称
        $obj->getActiveSheet()->setTitle('亚马逊补货预警信息');

        // 列标
        $list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA','AB','AC','AD','AE'];

        // 填充第一行数据
        $obj->getActiveSheet()
            ->setCellValue($list[0] . '1', '店铺')
            ->setCellValue($list[1] . '1', '运营')
            ->setCellValue($list[2] . '1', '销售状态')
            ->setCellValue($list[3] . '1', '品类')
            ->setCellValue($list[4] . '1', '性别')
            ->setCellValue($list[5] . '1', '父asin')
            ->setCellValue($list[6] . '1', 'SKU')
            ->setCellValue($list[7] . '1', '库存SKU')
            ->setCellValue($list[8] . '1', '在仓库存')
            ->setCellValue($list[9] . '1', '预留库存')
            ->setCellValue($list[10] . '1', '在途库存')
            ->setCellValue($list[11] . '1', '海外仓库存合计')
            ->setCellValue($list[12] . '1', '同安库存')
            ->setCellValue($list[13] . '1', '泉州库存')
            ->setCellValue($list[14] . '1', '云仓库存')
            ->setCellValue($list[15] . '1', '本地仓库存合计')
            ->setCellValue($list[16] . '1', '2021年销售')
            ->setCellValue($list[17] . '1', $beforeDate)
            ->setCellValue($list[18] . '1', $thisDate)
            ->setCellValue($list[19] . '1', '近两周销售')
            ->setCellValue($list[20] . '1', '2022年累计销售')
            ->setCellValue($list[21] . '1', '近一周日销')
            ->setCellValue($list[22] . '1', '近两周日销')
            ->setCellValue($list[23] . '1', '2021年度日销')
            ->setCellValue($list[24] . '1', '库存可周转天数')
            ->setCellValue($list[25] . '1', '补货提醒')
            ->setCellValue($list[26] . '1', '销售计划增长倍数')
            ->setCellValue($list[27] . '1', '快递')
            ->setCellValue($list[28] . '1', '海运')
            ->setCellValue($list[29] . '1', '空运')
            ->setCellValue($list[30] . '1', '合计');


        // 填充第n(n>=2, n∈N*)行数据
        $length = count($data);
        for ($i = 0; $i < $length; $i++) {
            $obj->getActiveSheet()->setCellValue($list[0] . ($i + 2), $data[$i]['shop_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[1] . ($i + 2), $data[$i]['operate_user'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[2] . ($i + 2), $data[$i]['category_status'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[3] . ($i + 2), $data[$i]['one_cate'].$data[$i]['two_cate'].$data[$i]['three_cate'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[4] . ($i + 2), '', \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[5] . ($i + 2), $data[$i]['father_asin'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[6] . ($i + 2), $data[$i]['sku'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[7] . ($i + 2), $data[$i]['custom_sku'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[8] . ($i + 2), $data[$i]['in_warehouse_inventory'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[9] . ($i + 2), $data[$i]['reserved_inventory'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[10] . ($i + 2), $data[$i]['in_road_inventory'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[11] . ($i + 2), $data[$i]['total_inventory'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[12] . ($i + 2), $data[$i]['self_delivery_inventory']+$data[$i]['tongAn_inventory'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[13] . ($i + 2), $data[$i]['quanzhou_inventory'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[14] . ($i + 2), $data[$i]['cloud_num'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[15] . ($i + 2), $data[$i]['self_delivery_inventory']+$data[$i]['tongAn_inventory']+$data[$i]['quanzhou_inventory']+$data[$i]['cloud_num'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[16] . ($i + 2), $data[$i]['lastyear_sales'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[17] . ($i + 2), $data[$i]['before_quantity_ordered'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[18] . ($i + 2), $data[$i]['quantity_ordered'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[19] . ($i + 2), $data[$i]['total_sales'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[20] . ($i + 2), $data[$i]['year_total'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[21] . ($i + 2), $data[$i]['this_week_daysales'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[22] . ($i + 2), $data[$i]['week_daysales'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[23] . ($i + 2), $data[$i]['last_year_daySales'], \PHPExcel_Cell_DataType::TYPE_STRING);
            if ($data[$i]['inventory_turnover'] < 0) $data[$i]['inventory_turnover'] = '';
            $obj->getActiveSheet()->setCellValue($list[24] . ($i + 2), $data[$i]['inventory_turnover'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $type = '';
            if(isset($data[$i]['buhuo_status'])){
                if ($data[$i]['buhuo_status'] == '1'){
                    $type = '需要补货';
                } elseif ($data[$i]['buhuo_status'] == '2'){
                    $type = '库存偏多';
                } elseif ($data[$i]['buhuo_status'] == '3'){
                    $type = '库存冗余';
                }
            }
            $obj->getActiveSheet()->setCellValue($list[25] . ($i + 2), $type, \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[26] . ($i + 2), $data[$i]['plan_multiple'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[27] . ($i + 2), $data[$i]['courier'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[28] . ($i + 2), $data[$i]['shipping'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[29] . ($i + 2), $data[$i]['air'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[30] . ($i + 2), $data[$i]['replenishment_total'], \PHPExcel_Cell_DataType::TYPE_STRING);

        }
        // 设置加粗和左对齐
        foreach ($list as $col) {
            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($col . '1')->getFont()->setBold(true);
            // 设置第1-n行，左对齐
            for ($i = 1; $i <= $length + 1; $i++) {
                $obj->getActiveSheet()->getStyle($col . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            }
        }
        // 设置列宽
        $obj->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('B')->setWidth(10);
        $obj->getActiveSheet()->getColumnDimension('C')->setWidth(10);
        $obj->getActiveSheet()->getColumnDimension('D')->setWidth(35);
        $obj->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        $obj->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('G')->setWidth(30);
        $obj->getActiveSheet()->getColumnDimension('H')->setWidth(30);
        $obj->getActiveSheet()->getColumnDimension('I')->setWidth(10);
        $obj->getActiveSheet()->getColumnDimension('J')->setWidth(10);
        $obj->getActiveSheet()->getColumnDimension('K')->setWidth(10);
        $obj->getActiveSheet()->getColumnDimension('L')->setWidth(10);
        $obj->getActiveSheet()->getColumnDimension('M')->setWidth(10);
        $obj->getActiveSheet()->getColumnDimension('N')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('O')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('P')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('Q')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('R')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('S')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('T')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('U')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('V')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('W')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('X')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('Y')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('Z')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('AA')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('AB')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('AC')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('AD')->setWidth(15);
        $obj->getActiveSheet()->getColumnDimension('AE')->setWidth(15);

        // 导出
        @ob_clean();
        if ($fileType == 'xls') {
            echo 1;
            die;
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xls');
            header('Cache-Control: max-age=1');
            $objWriter = new \PHPExcel_Writer_Excel5($obj);
            $objWriter->save('php://output');
            exit;
        } elseif ($fileType == 'xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');
            header('Cache-Control: max-age=1');
            $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
            $objWriter->save('php://output');
//            $objWriter->save('./admin/export/' . $fileName . '.xlsx');
            return [
                'type' => 'success',
                'msg' => $fileName . '.xlsx'
            ];
        }
    }

    public function deleteFile($path)
    {
        //清空文件夹函数和清空文件夹后删除空文件夹函数的处理
        //如果是目录则继续
        if (is_dir($path)) {
            //扫描一个文件夹内的所有文件夹和文件并返回数组
            $p = scandir($path);
            foreach ($p as $val) {
                //排除目录中的.和..
                if ($val != "." && $val != "..") {
                    //如果是目录则递归子目录，继续操作
                    if (is_dir($path . $val)) {
                        //子目录中操作删除文件夹和文件
                        $this->deleteFile($path . $val . '/');
                    } else {
                        //如果是文件直接删除
                        unlink($path . $val);
                    }
                }
            }
        }
    }

     //根据补货计划生成补货单
     public function create_buhuoDoc_autob($param)
     {
 //        return ['type'=>'fail','data'=>'系统紧急维护中，暂时无法发货，预计在上午10点左右恢复'];
         $data = $param['data'];
         $new_data = [];

         $request_type = $param['request_type']??1;

          
         $desc =  $param['desc']??'';


         //工厂直发仓补货  18229
         if($request_type==2){

            $param['warehouse'] = 21;
            $res = $this->create_buhuoDoc($param);
            if($res['type']!='success'){
                return ['type'=>'fail','data'=>$res['msg']];
            }

            $addtask['task_t_id'] = 18229;
            $addtask['user_fz'] = $param['user_fz'];
            $addtask['user_sh'] = $param['user_sh'];
            $addtask['user_cj'] = $param['user_cj'];
            $addtask['request_id'] = $res['data']['request_id'];
            $addtask['link'] = $res['data']['link'];
            $addtask['start_time'] = $param['start_time'];
            $addtask['end_time'] = $param['end_time'];

            $return['warehouse'] = 21;
            $return['order_id'] = $this->create_task($addtask);
            if($return['order_id']>0){
                DB::table('amazon_buhuo_request')->where('id', '=',$res['data']['request_id'])->update(['request_status' => 3]);
            }
            $return['name'] ='';
            $task = db::table('tasks')->where('id',$return['order_id'])->first();
            if($task){
                $return['name'] = $task->name;
                db::table('tasks')->where('id',$return['order_id'])->update(['desc'=>$desc]);
            }
            $return['desc'] = $desc;
            $taskres[] = $return;
         }
         

         $new_data['quanzhou']['request_num'] = 0;
         $new_data['tongan']['request_num'] = 0;
         $new_data['cloud']['request_num'] = 0;

 
         foreach ($data as $v) {
             # code...
             if(isset($v['quanzhou_auto_num'])&&$v['quanzhou_auto_num']>0){
                 $v['request_num'] = $v['quanzhou_auto_num'];
                 $new_data['quanzhou'][]= $v;
                 $new_data['quanzhou']['request_num']+=$v['quanzhou_auto_num'];
             }
             if(isset($v['tongan_auto_num'])&&$v['tongan_auto_num'] >0){
                 $v['request_num'] = $v['tongan_auto_num'];
                 $new_data['tongan'][]= $v;
                 $new_data['tongan']['request_num']+=$v['tongan_auto_num'];
             }
             if(isset($v['cloud_auto_num'])&&$v['cloud_auto_num'] >0){
                 $v['request_num'] = $v['cloud_auto_num'];
                 $new_data['cloud'][]= $v;
                 $new_data['cloud']['request_num']+=$v['cloud_auto_num'];
             }
         }
         //1.同安仓 2.泉州仓 3.云仓 4.工厂直发仓 18229
         if($new_data['tongan']['request_num']>0){
             $param['data'] = $new_data['tongan'];
             $param['warehouse'] = 1;
             $res = $this->create_buhuoDoc($param);
             if($res['type']!='success'){
                 return ['type'=>'fail','data'=>$res['msg']];
             }
 
             $addtask['task_t_id'] = 47;
             $addtask['user_fz'] = $param['user_fz'];
             $addtask['user_sh'] = $param['user_sh'];
             $addtask['user_cj'] = $param['user_cj'];
             $addtask['request_id'] = $res['data']['request_id'];
             $addtask['link'] = $res['data']['link'];
             $addtask['start_time'] = $param['start_time'];
             $addtask['end_time'] = $param['end_time'];
 
             $return['warehouse'] = 1;
             $return['order_id'] = $this->create_task($addtask);
             if($return['order_id']>0){
                 DB::table('amazon_buhuo_request')->where('id', '=',$res['data']['request_id'])->update(['request_status' => 3]);
             }
             $return['name'] ='';
             $task = db::table('tasks')->where('id',$return['order_id'])->first();
             if($task){
                 $return['name'] = $task->name;
                 db::table('tasks')->where('id',$return['order_id'])->update(['desc'=>$desc]);
             }
             $return['desc'] = $desc;
             $taskres[] = $return;
         }
         if($new_data['quanzhou']['request_num']>0){
             $param['data'] = $new_data['quanzhou'];
             $param['warehouse'] = 2;
             $res = $this->create_buhuoDoc($param);
             if($res['type']!='success'){
                 return ['type'=>'fail','data'=>$res['msg']];
             }
 
             $addtask['task_t_id'] = 440;
             $addtask['user_fz'] = $param['user_fz'];
             $addtask['user_sh'] = $param['user_sh'];
             $addtask['user_cj'] = $param['user_cj'];
             $addtask['request_id'] = $res['data']['request_id'];
             $addtask['link'] = $res['data']['link'];
             $addtask['start_time'] = $param['start_time'];
             $addtask['end_time'] = $param['end_time'];
             $return['warehouse'] = 2;
             $return['order_id'] = $this->create_task($addtask);
             if($return['order_id']>0){
                 DB::table('amazon_buhuo_request')->where('id', '=',$res['data']['request_id'])->update(['request_status' => 3]);
             }
 
             $return['name'] ='';
             $task = db::table('tasks')->where('id',$return['order_id'])->first();
             if($task){
                 $return['name'] = $task->name;
                 db::table('tasks')->where('id',$return['order_id'])->update(['desc'=>$desc]);
             }
             $return['desc'] = $desc;
             $taskres[] = $return;
         }
 
         if($new_data['cloud']['request_num']>0){
             $param['data'] = $new_data['cloud'];
             $param['warehouse'] = 3;
             $res = $this->create_buhuoDoc($param);
             if($res['type']!='success'){
                 return ['type'=>'fail','data'=>$res['msg']];
             }
 
             $addtask['task_t_id'] = 885;
             $addtask['user_fz'] = $param['user_fz'];
             $addtask['user_sh'] = $param['user_sh'];
             $addtask['user_cj'] = $param['user_cj'];
             $addtask['request_id'] = $res['data']['request_id'];
             $addtask['link'] = $res['data']['link'];
             $addtask['start_time'] = $param['start_time'];
             $addtask['end_time'] = $param['end_time'];
             $return['warehouse'] = 3;
             $return['order_id'] = $this->create_task($addtask);
             if($return['order_id']>0){
                 DB::table('amazon_buhuo_request')->where('id', '=',$res['data']['request_id'])->update(['request_status' => 3]);
             }
 
             $return['name'] ='';
             $task = db::table('tasks')->where('id',$return['order_id'])->first();
             if($task){
                 $return['name'] = $task->name;
                 db::table('tasks')->where('id',$return['order_id'])->update(['desc'=>$desc]);
             }
             $return['desc'] = $desc;
             $taskres[] = $return;
         }
 
         return ['type'=>'success','data'=>$taskres];
 
     }

    //根据补货计划生成补货单
    public function create_buhuoDoc_auto($param)
    {
//        return ['type'=>'fail','data'=>'系统紧急维护中，暂时无法发货，预计在下午2点左右恢复'];
        try {
            db::beginTransaction();
            $data = $param['data'];
            $new_data = [];

            $new_data['quanzhou']['request_num'] = 0;
            $new_data['tongan']['request_num'] = 0;
            $new_data['cloud']['request_num'] = 0;

            $desc =  $param['desc']??'';

            foreach ($data as $v) {
                # code...
                if(isset($v['quanzhou_auto_num'])&&$v['quanzhou_auto_num']>0){
                    $v['request_num'] = $v['quanzhou_auto_num'];
                    $new_data['quanzhou'][]= $v;
                    $new_data['quanzhou']['request_num']+=$v['quanzhou_auto_num'];
                }
                if(isset($v['tongan_auto_num'])&&$v['tongan_auto_num'] >0){
                    $v['request_num'] = $v['tongan_auto_num'];
                    $new_data['tongan'][]= $v;
                    $new_data['tongan']['request_num']+=$v['tongan_auto_num'];
                }
                if(isset($v['cloud_auto_num'])&&$v['cloud_auto_num'] >0){
                    $v['request_num'] = $v['cloud_auto_num'];
                    $new_data['cloud'][]= $v;
                    $new_data['cloud']['request_num']+=$v['cloud_auto_num'];
                }
            }
            //1.同安仓 2.泉州仓 3.云仓
            if($new_data['tongan']['request_num']>0){
                $param['data'] = $new_data['tongan'];
                $param['warehouse'] = 1;
                $res = $this->create_buhuoDoc($param);
                if($res['type']!='success'){
                    db::rollback();
                    return ['type'=>'fail','data'=>$res['msg']];
                }

//                $addtask['task_t_id'] = 47;
//                $addtask['user_fz'] = $param['user_fz'];
//                $addtask['user_sh'] = $param['user_sh'];
//                $addtask['user_cj'] = $param['user_cj'];
//                $addtask['request_id'] = $res['data']['request_id'];
//                $addtask['link'] = $res['data']['link'];
//                $addtask['start_time'] = $param['start_time'];
//                $addtask['end_time'] = $param['end_time'];
//
//                $return['warehouse'] = 1;
//                $return['order_id'] = $this->create_task($addtask);
//                if($return['order_id']>0){
//                    DB::table('amazon_buhuo_request')->where('id', '=',$res['data']['request_id'])->update(['request_status' => 3]);
//                }
//                $return['name'] ='';
//                $task = db::table('tasks')->where('id',$return['order_id'])->first();
//                if($task){
//                    $return['name'] = $task->name;
//                    db::table('tasks')->where('id',$return['order_id'])->update(['desc'=>$desc]);
//                }
//                $return['desc'] = $desc;
//                $taskres[] = $return;


                // 合并发货改动
                $saveTask = [
                    'class_id' => 127,
                    'user_fz' => $param['user_fz'],
                    'user_sh' => $param['user_sh'],
                    'user_cj' => $param['user_cj'],
                    'end_time' => $param['end_time'],
                    'start_time' => $param['start_time'],
                    'link' => $res['data']['link'],
                    'request_id' => $res['data']['request_id'],
                    'warehouse_id' => 1,
                    'warehouse_name' => '同安仓',
                ];

                $return['warehouse'] = 1;
                $return['order_id'] = $this->create_request_task($saveTask);
                if($return['order_id']>0){
                    DB::table('amazon_buhuo_request')->where('id', '=',$res['data']['request_id'])->update(['request_status' => 3]);
                }

                $return['name'] ='';
                $task = db::table('tasks')->where('id',$return['order_id'])->first();
                if($task){
                    $return['name'] = $task->name;
                    db::table('tasks')->where('id',$return['order_id'])->update(['desc'=>$desc]);
                }
                $return['desc'] = $desc;
                $taskres[] = $return;
            }
            if($new_data['quanzhou']['request_num']>0){
                $param['data'] = $new_data['quanzhou'];
                $param['warehouse'] = 2;
                $res = $this->create_buhuoDoc($param);
                if($res['type']!='success'){
                    db::rollback();
                    return ['type'=>'fail','data'=>$res['msg']];
                }

//                $addtask['task_t_id'] = 440;
//                $addtask['user_fz'] = $param['user_fz'];
//                $addtask['user_sh'] = $param['user_sh'];
//                $addtask['user_cj'] = $param['user_cj'];
//                $addtask['request_id'] = $res['data']['request_id'];
//                $addtask['link'] = $res['data']['link'];
//                $addtask['start_time'] = $param['start_time'];
//                $addtask['end_time'] = $param['end_time'];
//                $return['order_id'] = $this->create_task($addtask);

                $saveTask = [
                    'class_id' => 127,
                    'user_fz' => $param['user_fz'],
                    'user_sh' => $param['user_sh'],
                    'user_cj' => $param['user_cj'],
                    'end_time' => $param['end_time'],
                    'start_time' => $param['start_time'],
                    'link' => $res['data']['link'],
                    'request_id' => $res['data']['request_id'],
                    'warehouse_id' => 2,
                    'warehouse_name' => '泉州仓',
                ];

                $return['warehouse'] = 2;
                $return['order_id'] = $this->create_request_task($saveTask);
                if($return['order_id']>0){
                    DB::table('amazon_buhuo_request')->where('id', '=',$res['data']['request_id'])->update(['request_status' => 3]);
                }

                $return['name'] ='';
                $task = db::table('tasks')->where('id',$return['order_id'])->first();
                if($task){
                    $return['name'] = $task->name;
                    db::table('tasks')->where('id',$return['order_id'])->update(['desc'=>$desc]);
                }
                $return['desc'] = $desc;
                $taskres[] = $return;
            }

            if($new_data['cloud']['request_num']>0){
                $param['data'] = $new_data['cloud'];
                $param['warehouse'] = 3;
                $res = $this->create_buhuoDoc($param);
                if($res['type']!='success'){
                    db::rollback();
                    return ['type'=>'fail','data'=>$res['msg']];
                }

//                $addtask['task_t_id'] = 885;
//                $addtask['user_fz'] = $param['user_fz'];
//                $addtask['user_sh'] = $param['user_sh'];
//                $addtask['user_cj'] = $param['user_cj'];
//                $addtask['request_id'] = $res['data']['request_id'];
//                $addtask['link'] = $res['data']['link'];
//                $addtask['start_time'] = $param['start_time'];
//                $addtask['end_time'] = $param['end_time'];

                //                $return['order_id'] = $this->create_task($addtask);

                $saveTask = [
                    'class_id' => 127,
                    'user_fz' => $param['user_fz'],
                    'user_sh' => $param['user_sh'],
                    'user_cj' => $param['user_cj'],
                    'end_time' => $param['end_time'],
                    'start_time' => $param['start_time'],
                    'link' => $res['data']['link'],
                    'request_id' => $res['data']['request_id'],
                    'warehouse_id' => 3,
                    'warehouse_name' => '云仓',
                ];

                $return['order_id'] = $this->create_request_task($saveTask);
                $return['warehouse'] = 3;
                if($return['order_id']>0){
                    DB::table('amazon_buhuo_request')->where('id', '=',$res['data']['request_id'])->update(['request_status' => 3]);
                }

                $return['name'] ='';
                $task = db::table('tasks')->where('id',$return['order_id'])->first();
                if($task){
                    $return['name'] = $task->name;
                    db::table('tasks')->where('id',$return['order_id'])->update(['desc'=>$desc]);
                }
                $return['desc'] = $desc;
                $taskres[] = $return;
            }

            db::commit();
            return ['type'=>'success','data'=>$taskres];
        }catch(\Exception $e){
            db::rollback();
            return ['type' => 'fail', 'data' => $e->getMessage().'；位置：'.$e->getLine()];
        }
    }


    public function UpdateTaskName($param){
      
        $desc = $param['desc']??'';
        $task_id = $param['id'];
        $name = $param['name'];
        $is_repeat = db::table('tasks')->where('name',$name)->where('id','!=',$task_id )->first();
        if( $is_repeat){
            return['type'=>'fail','data'=>'该任务名重复'];
        }
        
        db::table('tasks')->where('id',$task_id)->update(['name'=>$name,'desc'=>$desc]);
        return ['type'=>'success','data'=>[]];
    }


    public function create_task($param){

         //1.同安仓 2.泉州仓 3.云仓
        // var_dump($param);
        // return 1;
        $task = new \App\Libs\wrapper\Task();

        $taskinfo =  $task->task_info(['task_id'=>$param['task_t_id']]);


        $res = $taskinfo['basic'];

        
        $res['node'] = $taskinfo['node'];


        // unset($taskinfo['usef_fz']);
        // var_dump($taskinfo);
        $res['user_fz'] =  $param['user_fz'];

        $res['user_cj'] =  $param['user_cj'];

        
        //节点1创货件负责人
        $res['node'][1]['node_task_data'][0]['account'] = $this->GetUsers($res['user_fz'])['account'];
        $res['node'][1]['node_task_data'][0]['phone'] = $this->GetUsers($res['user_fz'])['phone'];
        $res['node'][1]['node_task_data'][0]['user_id'] = $res['user_fz'];



        $res['Id'] = $param['task_t_id'];

        // var_dump($param['request_id']);
        $res['name'] = $taskinfo['basic']['name'].$param['request_id'].'-'.rand(1,100);
        // unset($taskinfo['basic']['name']);
        // var_dump( $res['name']);

        $ext['request_link'] =$param['link'];
        $ext['request_id']=(string)$param['request_id'];
        $ext['start_time']=$param['start_time'];
        $ext['end_time']=$param['end_time'];

        $res['ext'] = $ext;

        unset($res['examine']);
        // foreach ($taskinfo['basic']['examine'] as $v) {
        //     # code...
        //     $res['examine'][] = $v['user_id'];

        // }
        $res['examine'] = $param['user_sh'];

        // unset($taskinfo['basic']['examine']);
       
        // $res['user_fz'] = db::table('users')->where('account',$taskinfo['account_fz'])->first()->Id;

        // unset($taskinfo['account_fz']);
        $res['state'] = 1;
        $res['is_intervention'] = 2;


        // var_dump($res);
    
        $id = $task->task_add($res);

        // var_dump($id);

        if($id['type']=='success'){
            return $id['data'];
        }else{
            return 0;
        }
        // $res[]

        // state: 1
        // is_intervention: 2

    }

    public function create_request_task($param)
    {
        $taskMdl = db::table('tasks')
            ->where('class_id', $param['class_id'])
            ->where('type', 2)
            ->first();
        if (empty($taskMdl)){
            throw new \Exception('未查询到补货申请模板任务数据！');
        }
        $task = new \App\Libs\wrapper\Task();
        $taskinfo =  $task->task_info(['task_id'=>$taskMdl->Id]);

        $res = $taskinfo['basic'];
        $res['user_fz'] =  $param['user_fz'];
        $res['user_cj'] =  $param['user_cj'];
        $res['name'] = $param['warehouse_name'].'-'.$taskinfo['basic']['name'].$param['request_id'].'@'.date('y-m-d/H:i:s', microtime(true));
        $ext['request_link'] =$param['link'];
        $ext['request_id']=(string)$param['request_id'];
        $ext['start_time']=$param['start_time'];
        $ext['end_time']=$param['end_time'];
        $ext['warehouse_id']=$param['warehouse_id'];
        $ext['warehouse_name']=$param['warehouse_name'];
        $res['ext'] = $ext;
        unset($res['examine']);
        $res['examine'] = $param['user_sh'];
        $res['state'] = 1;
        $res['is_intervention'] = 2;
        $id = $task->task_add($res);
        if($id['type']=='success'){
            return $id['data'];
        }else{
            return 0;
        }
    }
    public function create_fba_shipment_task($param){
        try {
            //1.同安仓 2.泉州仓 3.云仓
            $task = new \App\Libs\wrapper\Task();

            $taskinfo =  $task->task_info(['task_id'=>$param['task_t_id']]);

            $res = $taskinfo['basic'];
            $res['audit_method'] = 4;

            $res['node'] = $taskinfo['node'];

            $res['user_fz'] =  $param['user_fz'];

            $res['user_cj'] =  $param['user_cj'];
            //节点1创货件负责人
            $res['node'][1]['node_task_data'][0]['account'] = $this->GetUsers($res['user_fz'])['account'];
            $res['node'][1]['node_task_data'][0]['phone'] = $this->GetUsers($res['user_fz'])['phone'];
            $res['node'][1]['node_task_data'][0]['user_id'] = $res['user_fz'];

            $res['name'] = $taskinfo['basic']['name'].$param['request_id'].'-'.rand(1,100);
            $ext['request_link'] =$param['link'];
            $ext['request_id']=(string)$param['request_id'];
            $ext['start_time']=$param['start_time'];
            $ext['end_time']=$param['end_time'];
            $res['ext'] = $ext;
            unset($res['examine']);
            $res['examine'] = [];
            $res['state'] = 3;
            $res['is_intervention'] = 2;
            $res['time_examine'] = date('Y-m-d H:i:s', microtime(true));


            // var_dump($res);
            $id = $task->task_add($res);

            if($id['type']=='success'){
                return $id['data'];
            }else{
                return 0;
            }
        }catch (\Exception $e){
            throw new \Exception('任务创建失败！原因：'.$e->getMessage().'，位置：'. $e->getLine());
        }
    }

    //根据补货计划生成补货单
    public function create_buhuoDoc($param)
    {
        $data = $param['data'];
        $token = $param['token'];
        $warehouse = isset($param['warehouse']) ? $param['warehouse'] : 1;
        $tag = isset($param['tag']) ? $param['tag'] : 0;
//        if($warehouse==3){
//            return ['type' => 'fail', 'msg' => '云仓暂时停止发货'];
//        }
        if (!isset($param['user_name'])) return ['type' => 'fail', 'msg' => '未给定申请人名称！'];
        if (!isset($param['user_id'])) return ['type' => 'fail', 'msg' => '未给定申请人标识！'];
        $user_name = $param['user_name'];
        $user_id = $param['user_id'];

        if (!empty($data)) {
            $request_time = date('Y-m-d H:i:s');//申请时间
            $delivery_date = date('Y-m-d');//发货时间
            if(!isset($param['transportation_id'])){
                return ['type' => 'fail', 'msg' => '请选择运输方式！！'];
            }
            $transportationMdl = $this->transportationModeModel::query()
                ->where('id', $param['transportation_id'])
                ->first();
            if (empty($transportationMdl)){
                return ['type' => 'fail', 'msg' => '运输方式不存在！'];
            }
            $transportation_date = date("Y-m-d", strtotime("+{$transportationMdl->expected_duration} day"));;
            $shop_id = $data[0]['shop_id'];
//            $_SERVER['SERVER_NAME'].
            if ($user_id != 0 && $shop_id != 0) {
                $shopData = $this->GetShop($shop_id);
                if($shopData){
                    $platform_id = $shopData['platform_id'];
                }else{
                    $platform_id = 0;
                }
                db::beginTransaction();    //开启事务
                //创建补货单
                $insert_id = DB::table('amazon_buhuo_request')->insertGetId(['shop_id' => $shop_id, 'request_userid' => $user_id, 'warehouse'=> $warehouse,
                    'request_time' => $request_time, 'delivery_date' => $delivery_date, 'update_time' => $request_time, 'update_user' => $user_name ,'tag'=>$tag,'transportation_mode_name' => $transportationMdl->name, 'transportation_date' => $transportation_date]);
                if (isset($insert_id)) {
                    //补货单详情链接
                    $request_link = '/amazon_buhuo_data?id=' . $insert_id;
                    $a = 0;
                    $b = 0;
                    $request_total_num = 0;

//                    // 合并发货后操作
                    $box_code = $this->Addbox($insert_id,$warehouse);//新增任务中转箱


                    foreach ($data as $val) {
//                        if($val['spu_id']==244){
//                            db::rollback();// 回调
//                            return ['type' => 'fail', 'msg' => $val['spu'].'的货物盘点中，暂时无法创建订单'];
//                        }
                        $custom_sku = $val['custom_sku'];
                        if($val['sputype']==2){
                            $cloud_sku[] = $custom_sku;
                        }
                        if ($val['request_num'] == 0){
                            continue;
                        } else {
                            $create_time = time();


                            //仓储改动

                            // 合并发货后操作
                            if($warehouse==1||$warehouse==2){
                                if($box_code){
//                                    if($val['sputype']==2){
//                                       $zuhe_ustom_sku = $this->GetGroupCustomSku($custom_sku);
//                                       if($zuhe_ustom_sku){
//                                           foreach ($zuhe_ustom_sku as $zuhe){
//                                               $res = $this->PointsLocation($zuhe['group_custom_sku_id'],$warehouse,$val['request_num'],$box_code,$zuhe['group_custom_sku'],$platform_id,6);
//                                               if($res!=1){
//                                                   return ['type' => 'fail', 'msg' => $res];
//                                               }
//                                           }
//                                       }else{
//                                           return ['type' => 'fail', 'msg' => $custom_sku.'获取子sku失败！'];
//                                       }
//                                    }else{
                                        $res = $this->PointsLocation($val['custom_sku_id'],$warehouse,$val['request_num'],$box_code,$custom_sku,$platform_id,6, 1);
                                        if($res!=1){
                                            return ['type' => 'fail', 'msg' => $res];
                                        }
//                                    }
                                }else{
                                    return ['type' => 'fail', 'msg' => '新增出库任务失败！'];
                                }
                            }

//                            if($warehouse==1||$warehouse==2){
//                                if($box_code){
//                                    if($val['sputype']==2){
//                                       $zuhe_ustom_sku = $this->GetGroupCustomSku($custom_sku);
//                                       if($zuhe_ustom_sku){
//                                           foreach ($zuhe_ustom_sku as $zuhe){
//                                               $res = $this->PointsLocation($zuhe['group_custom_sku_id'],$warehouse,$val['request_num'],$box_code,$zuhe['group_custom_sku'],$platform_id,6);
//                                               if($res!=1){
//                                                   return ['type' => 'fail', 'msg' => $res];
//                                               }
//                                           }
//                                       }else{
//                                           return ['type' => 'fail', 'msg' => $custom_sku.'获取子sku失败！'];
//                                       }
//                                    }else{
//                                        $res = $this->PointsLocation($val['custom_sku_id'],$warehouse,$val['request_num'],$box_code,$custom_sku,$platform_id,
//                                            6,1);
//                                        if($res!=1){
//                                            return ['type' => 'fail', 'msg' => $res];
//                                        }
//                                    }
//                                }else{
//                                    return ['type' => 'fail', 'msg' => '新增出库任务失败！'];
//                                }
//                            }

                            //改动结束



                            $insert_detail = DB::table('amazon_buhuo_detail')->insert(
                                [
                                    'request_id' => $insert_id,
                                    'sku' => $val['sku'],
                                    'request_num' => $val['request_num'],
                                    'spu_id'=>$val['spu_id'],
                                    'custom_sku_id'=>$val['custom_sku_id'],
                                    'create_time' => $create_time,
                                    'custom_sku' => $custom_sku,
                                    'sku_id'=>$val['sku_id'],
                                    'user_id'=>$val['user_id'],
                                    'spu' => $val['spu'],
                                    'shop_id' => $shop_id,
                                    'transportation_mode_name' => $transportationMdl->name, // 便于计算和展示
                                    'transportation_type' => $transportationMdl->type
                                ]);
                            if ($insert_detail) {
                                $a++;
                            }else{
                                db::rollback();// 回调
                                return ['type' => 'fail', 'msg' => '新增补货明细失败！--'.$custom_sku];
                            }
                            $request_total_num+=$val['request_num'];

                            //仓储改动
//                            if($val['sputype']==2) {
//                                foreach ($zuhe_ustom_sku as $zh) {
//                                    $spudata = $this->GetCustomSkus($zh['group_custom_sku']);
//                                    $insert_goods_detail = DB::table('goods_transfers_detail')->insert([
//                                        'order_no' => $insert_id,
//                                        'spu' => $spudata['spu'],
//                                        'custom_sku' => $zh['group_custom_sku'],
//                                        'transfers_num' => $val['request_num'],
//                                        'createtime' => $request_time,
//                                        'spu_id' => $spudata['spu_id'],
//                                        'custom_sku_id' => $zh['group_custom_sku_id']
//                                    ]);
//                                    if(!$insert_goods_detail){
//                                        db::rollback();// 回调
//                                        return ['type' => 'fail', 'msg' => '新增清单明细失败！--'.$zh['group_custom_sku']];
//                                    }
//                                }
//                            }else{


//                                // 合并发货后操作
                                $insert_goods_detail = DB::table('goods_transfers_detail')->insert([
                                    'order_no'=> $insert_id,
                                    'spu'=>$val['spu'],
                                    'custom_sku'=>$custom_sku,
                                    'transfers_num'=>$val['request_num'],
                                    'createtime'=>$request_time,
                                    'spu_id'=>$val['spu_id'],
                                    'custom_sku_id'=>$val['custom_sku_id']
                                ]);
                                if(!$insert_goods_detail){
                                    db::rollback();// 回调
                                    return ['type' => 'fail', 'msg' => '新增清单明细失败！--'.$custom_sku];
                                }
//                            }

                            //改动结束



                        }
                    }
                    DB::table('amazon_buhuo_request')->where('id', '=', $insert_id)->update(['request_link' => $request_link]);
                    //如果是发云仓的计划并且存在组合sku则同步商品给云仓
                    if($warehouse==3){
                        if(isset($cloud_sku)){
                            $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                            $cloud::sendJob($cloud_sku);
                        }
                    }

                }

//                //仓储改动
                // 合并发货后操作
                $insert_goods_transfers = DB::table('goods_transfers')->insert(
                    [
                        'order_no'=>$insert_id,
                        'user_id'=>$user_id,
                        'createtime'=>$request_time,
                        'total_num'=>$request_total_num,
                        'out_house'=>$warehouse,
                        'in_house'=>20,//亚马逊海外仓
                        'is_push'=>2,
                        'type'=>2,
                        'type_detail'=>6,
                        'shop_id'=>$shop_id,
                        'platform_id'=>5,
                    ]);
                if(!$insert_goods_transfers){
                    db::rollback();// 回调
                    return ['type' => 'fail', 'msg' => '新增清单失败'];
                }
//                //改动结束

            }

            if (isset($insert_id) && $a != 0) {
                db::commit();
                return ['type' => 'success',
                    'msg' => '补货单创建成功，本次将补货' . $a . '个sku',
                    'data' => ['link' => $request_link, 'request_id' => $insert_id]
                ];
            }  else {
                return ['type' => 'fail', 'msg' => '补货单创建失败'];
            }
        }

    }


    //回填走船，到港时间
    public function UpBuhuoBoat_time($params){
        if(isset($params['runboat_time'])){
            $up['runboat_time'] = $params['runboat_time'];
        }
        if(isset($params['arrival_time'])){
            $up['arrival_time'] = $params['arrival_time'];
        }
 

        $request_id = $params['request_id'];

        
        db::table('amazon_buhuo_request')->whereIn('id',$request_id)->where('request_type',2)->update($up);
        return ['type' => 'success', 'msg' => '修改成功'];
    }



     //根据补货计划生成补货单
     public function create_buhuoDocb($param)
     {

        // return ['type' => 'success',
        // 'msg' => '补货单创建成功，本次将补货10个sku',
        // 'data' => ['link' => '/transfer_request_details?order_no=7201698292879', 'request_id' => 111,'data'=>$param]
        // ];

         $data = $param['data'];
         $token = $param['token'];
         $warehouse = 21;
         $tag = isset($param['tag']) ? $param['tag'] : 0;
 //        if($warehouse==3){
 //            return ['type' => 'fail', 'msg' => '云仓暂时停止发货'];
 //        }
         if (!isset($param['user_name'])) return ['type' => 'fail', 'msg' => '未给定申请人名称！'];
         if (!isset($param['user_id'])) return ['type' => 'fail', 'msg' => '未给定申请人标识！'];
         $user_name = $param['user_name'];
         $user_id = $param['user_id'];
 
         if (!empty($data)) {
             $request_time = date('Y-m-d H:i:s');//申请时间
             $delivery_date =$param['delivery_date']??date('Y-m-d');//发货时间
             if(!isset($param['transportation_id'])){
                 return ['type' => 'fail', 'msg' => '请选择运输方式！！'];
             }
             $transportationMdl = $this->transportationModeModel::query()
                 ->where('id', $param['transportation_id'])
                 ->first();
             if (empty($transportationMdl)){
                 return ['type' => 'fail', 'msg' => '运输方式不存在！'];
             }
             $transportation_date = date("Y-m-d", strtotime("+{$transportationMdl->expected_duration} day"));;
             $shop_id = $data[0]['shop_id'];
 //            $_SERVER['SERVER_NAME'].
             if ($user_id != 0 && $shop_id != 0) {
                 $shopData = $this->GetShop($shop_id);
                 if($shopData){
                     $platform_id = $shopData['platform_id'];
                 }else{
                     $platform_id = 0;
                 }
                 db::beginTransaction();    //开启事务
                 //创建补货单
                 $insert_id = DB::table('amazon_buhuo_request')->insertGetId(['shop_id' => $shop_id, 'request_userid' => $user_id, 'warehouse'=> $warehouse,
                     'request_time' => $request_time, 'delivery_date' => $delivery_date,'request_type'=>2,'update_time' => $request_time, 'update_user' => $user_name ,'tag'=>$tag,'transportation_mode_name' => $transportationMdl->name, 'transportation_date' => $transportation_date]);
                 if (isset($insert_id)) {
                     //补货单详情链接
                     $request_link = '/amazon_buhuo_data?id=' . $insert_id;
                     $a = 0;
                     $b = 0;
                     $request_total_num = 0;
                     $box_code = $this->Addbox($insert_id,$warehouse);//新增任务中转箱

                     $cus_data = [];

                     foreach ($data as $val) {
 //                        if($val['spu_id']==244){
 //                            db::rollback();// 回调
 //                            return ['type' => 'fail', 'msg' => $val['spu'].'的货物盘点中，暂时无法创建订单'];
 //                        }
                         $custom_sku = $val['custom_sku'];
                         if($val['sputype']==2){
                             $cloud_sku[] = $custom_sku;
                         }
                         if ($val['request_num'] == 0){
                             continue;
                         } else {
                             $create_time = time();
                             //仓储改动
                             if($warehouse==1||$warehouse==2){
                                 if($box_code){
 //                                    if($val['sputype']==2){
 //                                       $zuhe_ustom_sku = $this->GetGroupCustomSku($custom_sku);
 //                                       if($zuhe_ustom_sku){
 //                                           foreach ($zuhe_ustom_sku as $zuhe){
 //                                               $res = $this->PointsLocation($zuhe['group_custom_sku_id'],$warehouse,$val['request_num'],$box_code,$zuhe['group_custom_sku'],$platform_id,6);
 //                                               if($res!=1){
 //                                                   return ['type' => 'fail', 'msg' => $res];
 //                                               }
 //                                           }
 //                                       }else{
 //                                           return ['type' => 'fail', 'msg' => $custom_sku.'获取子sku失败！'];
 //                                       }
 //                                    }else{
                                         $res = $this->PointsLocation($val['custom_sku_id'],$warehouse,$val['request_num'],$box_code,$custom_sku,
                                             $platform_id,6,1);
                                         if($res!=1){
                                             return ['type' => 'fail', 'msg' => $res];
                                         }
 //                                    }
                                 }else{
                                     return ['type' => 'fail', 'msg' => '新增出库任务失败！'];
                                 }
                             }
                             //改动结束
 
                             $insert_detail = DB::table('amazon_buhuo_detail')->insert(
                                 [
                                     'request_id' => $insert_id,
                                     'sku' => $val['sku'],
                                     'request_num' => $val['request_num'],
                                     'spu_id'=>$val['spu_id'],
                                     'custom_sku_id'=>$val['custom_sku_id'],
                                     'create_time' => $create_time,
                                     'custom_sku' => $custom_sku,
                                     'sku_id'=>$val['sku_id'],
                                     'user_id'=>$val['user_id'],
                                     'spu' => $val['spu'],
                                     'order_id'=>$val['order_id'],
                                     'shop_id' => $shop_id,
                                     'transportation_mode_name' => $transportationMdl->name, // 便于计算和展示
                                     'transportation_type' => $transportationMdl->type
                                 ]);
                             if ($insert_detail) {
                                 $a++;
                             }else{
                                 db::rollback();// 回调
                                 return ['type' => 'fail', 'msg' => '新增补货明细失败！--'.$custom_sku];
                             }

                             //装箱数据
                             $c_data['shop_id'] =  $shop_id;
                             $c_data['custom_sku'] = $custom_sku;
                             $c_data['spu_id'] = $val['spu_id'];
                             $c_data['spu'] = $val['spu'];
                             $c_data['user_id'] = $val['user_id'];
                             $c_data['custom_sku_id'] = $val['custom_sku_id'];
                             $c_data['order_id'] = $val['order_id'];
                             $c_data['request_num'] = $val['request_num'];
                             $c_data['request_id'] = $insert_id;
                             $c_data['sku'] = $val['sku'];
                             $c_data['sku_id'] = $val['sku_id'];

                             $cus_data[] = $c_data;
                             $request_total_num+=$val['request_num'];
 
                             //仓储改动
 //                            if($val['sputype']==2) {
 //                                foreach ($zuhe_ustom_sku as $zh) {
 //                                    $spudata = $this->GetCustomSkus($zh['group_custom_sku']);
 //                                    $insert_goods_detail = DB::table('goods_transfers_detail')->insert([
 //                                        'order_no' => $insert_id,
 //                                        'spu' => $spudata['spu'],
 //                                        'custom_sku' => $zh['group_custom_sku'],
 //                                        'transfers_num' => $val['request_num'],
 //                                        'createtime' => $request_time,
 //                                        'spu_id' => $spudata['spu_id'],
 //                                        'custom_sku_id' => $zh['group_custom_sku_id']
 //                                    ]);
 //                                    if(!$insert_goods_detail){
 //                                        db::rollback();// 回调
 //                                        return ['type' => 'fail', 'msg' => '新增清单明细失败！--'.$zh['group_custom_sku']];
 //                                    }
 //                                }
 //                            }else{
                                 $insert_goods_detail = DB::table('goods_transfers_detail')->insert([
                                     'order_no'=> $insert_id,
                                     'spu'=>$val['spu'],
                                     'custom_sku'=>$custom_sku,
                                     'transfers_num'=>$val['request_num'],
                                     'createtime'=>$request_time,
                                     'spu_id'=>$val['spu_id'],
                                     'custom_sku_id'=>$val['custom_sku_id']
                                 ]);
                                 if(!$insert_goods_detail){
                                     db::rollback();// 回调
                                     return ['type' => 'fail', 'msg' => '新增清单明细失败！--'.$custom_sku];
                                 }
 //                            }
 
                             //改动结束
 
                         }
                     }
                     DB::table('amazon_buhuo_request')->where('id', '=', $insert_id)->update(['request_link' => $request_link]);
                     //如果是发云仓的计划并且存在组合sku则同步商品给云仓
                     if($warehouse==3){
                         if(isset($cloud_sku)){
                             $cloud = new \App\Http\Controllers\Jobs\CloudHouseController();
                             $cloud::sendJob($cloud_sku);
                         }
                     }
 
                 }
 
                 //仓储改动
                 $insert_goods_transfers = DB::table('goods_transfers')->insert(
                     [
                         'order_no'=>$insert_id,
                         'user_id'=>$user_id,
                         'createtime'=>$request_time,
                         'total_num'=>$request_total_num,
                         'out_house'=>$warehouse,
                         'in_house'=>20,//亚马逊海外仓
                         'is_push'=>2,
                         'type'=>2,
                         'type_detail'=>6,
                         'shop_id'=>$shop_id,
                         'platform_id'=>5,
                     ]);
                 if(!$insert_goods_transfers){
                     db::rollback();// 回调
                     return ['type' => 'fail', 'msg' => '新增清单失败'];
                 }
                 //改动结束
 
             }
 
             if (isset($insert_id) && $a != 0) {

                //自动装箱
               $autobox =  $this->autoBox($cus_data);

                if($autobox['type']=='fail'){
                    return ['type'=>'fail','msg'=> $autobox['msg']];
                }


                 db::commit();
                 return ['type' => 'success',
                     'msg' => '补货单创建成功，本次将补货' . $a . '个sku',
                     'data' => ['link' => $request_link, 'request_id' => $insert_id]
                 ];
             }  else {
                 return ['type' => 'fail', 'msg' => '补货单创建失败'];
             }
         }
 
     }


     //自动装箱
     public function autoBox($params){

        // print_r($params);
        $i = 1;
        $num_js = [];
        $box_ids = [];
        foreach ($params as &$v) {
            # code...
            $custom_sku_id = $v['custom_sku_id'];
            $order_id = $v['order_id'];
            $sku_id = $v['sku_id'];
            $request_num = $v['request_num'];
            $request_id = $v['request_id'];
            $user_id = $v['user_id']??1;

            //根据单号查询箱规
            $supplier_s = db::table('cloudhouse_contract_total as a')->leftjoin('cloudhouse_contract as b','a.contract_no','=','b.contract_no')->where('b.order_id',$order_id)->select('a.id','b.id as tid','a.supplier_id')->first();
            $supplier_id = 0;
            if($supplier_s){
                $supplier_id =$supplier_s->supplier_id;
            }
            $box = db::table('self_custom_sku_box')->where('suppliers_id',$supplier_id)->where('custom_sku_id',$custom_sku_id)->first();

            $v['supplier_id'] = $supplier_id;
            if(!$box){
                return ['type' => 'fail', 'msg' => '自动装箱失败，无此箱规，订单号'.$order_id.',供应商id'.$supplier_id.'--'.'库存skuid'.$custom_sku_id.'res:'.json_encode($supplier_s)];
            }
            $box_ids[$custom_sku_id] = $box->id;

            //计算单件重量+外箱重量不能超过21.5kg
            // $weight = 21.5-$box->box_weight;

            // $product_weight_total = $box->num*$box->product_weight;

            $box_num = $box->num;

            //如果数量重量超过箱重，则去最大数量
            // if($product_weight_total>$weight){
            //     $box_num = ceil($weight/$box->product_weight);
            // }

           

            do {
                # code...
                $a = false;
                if($request_num>0){
                    if($box_num>$request_num){
                        $num = $request_num;
                    }else{
                        $num = $box_num;
                        $a = true;
                    }
    
                    $request_num-=$num;

                    // for ($in=0; $in < $i; $in++) { 
                    //     # code...
                    //     $num_js[$in] = 0;
                    //     if()
                    // }

                    $num_js[$sku_id][$i] = $num;
                   
                    $heavy =round($num*$box->product_weight+$box->box_weight,2);


                    db::table('amazon_box_data')->insert(['request_id'=>$request_id,'box_id'=>$i,'box_num'=> $num,'Long'=>$box->box_size_length,'wide'=>$box->box_size_wide,'high'=>$box->box_size_hight,'heavy'=>$heavy]);
                    // $i_detail['cus_box_id'] =  $box->id;
                    // $i_detail['request_id'] =  $request_id;
                    // $i_detail['box_no'] =  $i;
                    // $i_detail['custom_sku_id'] =  $v['custom_sku_id'];
                    // $i_detail['custom_sku'] =  $v['custom_sku'];
                    // $i_detail['spu_id'] =  $v['spu_id'];
                    // $i_detail['spu'] =  $v['spu'];
                    // $i_detail['shop_id'] = $v['shop_id'];
                    // $i_detail['user_id'] =  $user_id;
                    // $i_detail['num'] =  $num;
                    // $i_detail['actual_num'] =  $num;
                    // $i_detail['sku'] =  $v['sku'];
                    // $i_detail['sku_id'] =  $v['sku_id'];
                    // $i_detail['created_at'] =  date('Y-m-d H:i:s',time());

                    // db::table('amazon_box_data_detail')->insert($i_detail);
                    $i++;
                }

                // db::table('amazon_buhuo_detail')->where('request_id',$request_id)->where('sku_id',$v['sku_id'])->update(['cus_box_id'=>$box->id]);
               
            } while ($a);

        }

        // var_dump($num_js);
    
        // var_dump($i);
        foreach ($params as $vs) {
            # code...
            $sku_id = $vs['sku_id'];
            $custom_sku_id = $vs['custom_sku_id'];
            $n_js = [];

            $ki = 0;

            $num_arr = $num_js[$sku_id];


            for ($inu=1; $inu < $i; $inu++) { 
                # code...
                $n_js[$ki] = 0;
                // if(isset($num_arr[$inu])){
                //     $n_js[$ki] = $num_arr[$inu];
                // }
                foreach ($num_arr as $key => $value) {
                    # code...
                    if($key==$inu){
                        $n_js[$ki] = $value;
                    }
                }
                $ki++;
            }

            // var_dump($n_js);
                    
            $td['num'] = $n_js;
            $td['num_arr'] = $num_arr;
            $td['num_js'] = $num_js;
            $td['custom_sku_id'] = $custom_sku_id;
            $box_detail = json_encode($n_js);
            db::table('amazon_buhuo_detail')->where('request_id',$request_id)->where('sku_id',$vs['sku_id'])->update(['box_data_detail'=>$box_detail,'cus_box_id'=> $box_ids[$custom_sku_id],'supplier_id'=>$vs['supplier_id']]);
            # code...
        }


        
        return ['type'=>'success'];


     }


     public function amazon_buhuo_plan_new($params){

        $data = $params['data'];
        $delivery_date =$params['delivery_date']??date('Y-m-d');//发货时间
        $tag = isset($params['tag']) ? $params['tag'] : 0;
        $user_id = $params['user_id']??0;
        $user_fz = $params['user_fz']??0;
        $user_sh = $params['user_sh'];
        $start_time = $params['start_time'];
        $end_time = $params['end_time'];

        if(!isset($params['transportation_id'])){
            return ['type' => 'fail', 'msg' => '请选择运输方式！！'];
        }
        $transportationMdl = $this->transportationModeModel::query()
            ->where('id', $params['transportation_id'])
            ->first();
        if (empty($transportationMdl)){
            return ['type' => 'fail', 'msg' => '运输方式不存在！'];
        }


        $sup_data = [];
        $all_data = [];

        $check_cus = [];

        $shop_ids = [];
        foreach ($data as $v) {
            # code...
            $sku_id = $v['sku_id'];
            $request_num = $v['request_num']??0;

            $check_cus_res = db::table('self_sku')->where('id',$sku_id)->first();
            if(!$check_cus_res){
                return ['type'=>'fail','msg'=>'无此sku'.$sku_id];
            }
            

            //验证 不允许有重复库存sku
            if(isset($check_cus[$check_cus_res->custom_sku_id])){
                return ['type'=>'fail','msg'=>'存在重复库存sku'.$check_cus_res->sku.'--'.$check_cus[$check_cus_res->custom_sku_id]];
            }else{
                $check_cus[$check_cus_res->custom_sku_id] = $check_cus_res->sku;
            }
            $c_data = db::table('self_sku as a')->leftjoin('cloudhouse_custom_sku as b','a.custom_sku_id','=','b.custom_sku_id')->leftjoin('cloudhouse_contract_total as c','b.contract_no','=','c.contract_no')->where('b.order_id','>',0)->where('c.contract_status',2)->where('a.id',$sku_id)->select('a.id as sku_id','a.sku','a.custom_sku','a.custom_sku_id','a.spu','a.spu_id','a.shop_id','b.order_id','b.num','c.supplier_id','c.contract_no','c.report_date')->get();
            //根据合同交期 排序

            $c_data = json_decode(json_encode($c_data),true);

            usort($c_data, function($a, $b) {
                return strtotime($a['report_date']) - strtotime($b['report_date']);
            });


            //查询各供应商已下单量
            $sp_out_res = db::table('amazon_buhuo_detail as a')->leftjoin('amazon_buhuo_request as b','a.request_id','=','b.id')->where('a.custom_sku_id',$check_cus_res->custom_sku_id)->where('b.request_status','!=',1)->where('b.request_type',2)->select('a.request_num','a.supplier_id')->get();
            $sp_out_num = [];

            foreach ($sp_out_res as $spv) {
                # code...
                if(isset($sp_out_num[$spv->supplier_id])){
                    $sp_out_num[$spv->supplier_id]+=$spv->request_num;
                }else{
                    $sp_out_num[$spv->supplier_id]=$spv->request_num;
                }
            }


            //分配出库量
            foreach ($c_data as &$cv) {
                //如果有出库数据  则累计减去该出库数  
                if(isset($sp_out_num[$cv['supplier_id']])){
                    if($sp_out_num[$cv['supplier_id']]>=$cv['num']){
                        $cv['num'] = 0;
                        $sp_out_num[$cv['supplier_id']]-=$cv['num'];
                    }else{
                        $cv['num'] = $cv['num']-$sp_out_num[$cv['supplier_id']];
                    }
                }
                
                //如果还有余数
                if($cv['num']>0){
                    $cv['out_num'] = 0;
                    if($request_num>0){
                        if($request_num>$cv['num']){
                            $out_num = $cv['num'];
                        }else{
                            $out_num = $request_num;
                        }
                        $request_num -=$out_num;
                        $cv['out_num'] = $out_num;
                        $all_data[$cv['supplier_id']][] = $cv;
                    }
              
                }

              
                $shop_ids[$cv['supplier_id']] = $cv['shop_id']??0;
                # code...
        
            }


            $sup_data[] = $c_data;
        }


        //下单
        $request_ids=[];

        $rt_data = [];


        // var_dump($all_data);

        //合并不同下单，但相同sku的数据
        foreach ($all_data as &$adv) {

            $all_son_data = [];
            foreach ($adv as $advv) {
                if(isset($all_son_data[$advv['sku_id']])){
                    
                    $all_son_data[$advv['sku_id']]['out_num']+=$advv['out_num'];
                    $all_son_data[$advv['sku_id']]['num']+=$advv['num'];
                    $all_son_data[$advv['sku_id']]['order_id'].=','.$advv['order_id'];
                    $all_son_data[$advv['sku_id']]['contract_no'].=','.$advv['contract_no'];
                }else{
                    $all_son_data[$advv['sku_id']] = $advv;
                }

                # code...
            }
            $adv = [];

            $adv = array_values($all_son_data);
        }

        // var_dump($all_data);
        // return;
        db::beginTransaction();  

        foreach ($all_data as $r_supplier_id => $r_data) {
            # code...

            $user_fz = $params['user_fz']??0;
            $user_sh = $params['user_sh'];
            $start_time = $params['start_time'];
            $end_time = $params['end_time'];


            $FactoryBuhuoOrder_data['supplier_id'] = $r_supplier_id;
            $FactoryBuhuoOrder_data['transportation_mode_name'] = $transportationMdl->name;
            $FactoryBuhuoOrder_data['data'] = $r_data;
            $FactoryBuhuoOrder_data['delivery_date'] = $delivery_date;
            $FactoryBuhuoOrder_data['tag'] = $tag;
            $FactoryBuhuoOrder_data['user_id'] = $user_id;
            $FactoryBuhuoOrder_data['shop_id'] = $shop_ids[$r_supplier_id];
            $FactoryBuhuoOrder_data['user_fz'] = $user_fz;
            $FactoryBuhuoOrder_data['user_sh'] = $user_sh;
            $FactoryBuhuoOrder_data['start_time'] = $start_time;
            $FactoryBuhuoOrder_data['end_time'] = $end_time;


            try {
                //code...
                $Factory_order = $this->FactoryBuhuoOrder($FactoryBuhuoOrder_data);
            } catch (\Throwable $th) {
                //throw $th;
                db::rollback();// 回调
                return ['type'=>'fail','msg'=>$th->getLine().'--'.$th->getMessage()];
            }
    

           if($Factory_order['type']=='fail'){
             db::rollback();// 回调
             return ['type'=>'fail','msg'=>$Factory_order['msg']];
           }

           $rt_data_one['name'] ='';
           $task = db::table('tasks')->where('id',$Factory_order['task_id'])->first();
           if($task){
               $rt_data_one['name'] = $task->name;
               $rt_data_one['desc'] = $task->desc;
               $rt_data_one['order_id'] = $Factory_order['task_id'];
               $rt_data_one['task_id'] = $Factory_order['task_id'];
           }

           $rt_data[] = $rt_data_one;

           $request_ids[] = $Factory_order['request_id'].'task_id:'.$Factory_order['task_id'];
           
        }

        db::commit();

        return ['type'=>'success','data'=>['all_data'=>$all_data,'request_ids'=>$request_ids,'data'=>$rt_data],'msg'=>'获取成功'];

     }


     public function FactoryBuhuoOrder($params){

        $supplier_id = $params['supplier_id'];
        $data = $params['data'];
        $request_time = date('Y-m-d H:i:s');//申请时间
        $delivery_date =$param['delivery_date']??date('Y-m-d');//发货时间
        $tag = isset($param['tag']) ? $param['tag'] : 0;
        $user_id = $params['user_id'];
        $user_name = $this->GetUsers($user_id)['account'];
        $shop_id = $params['shop_id'];

        $user_fz = $params['user_fz'];

        $user_sh = $params['user_sh'];

        $start_time = $params['start_time'];

        $end_time = $params['end_time'];
        $transportation_mode_name = $params['transportation_mode_name'];




        $warehouse = 21;
        $create_time = time();

      
   
        // db::beginTransaction();  
        //创建补货单
        $insert_id = DB::table('amazon_buhuo_request')->insertGetId(['shop_id' => $shop_id, 'request_userid' => $user_id, 'warehouse'=> $warehouse,
        'request_time' => $request_time, 'delivery_date' => $delivery_date,'request_type'=>2,'update_time' => $request_time, 'update_user' => $user_name ,'tag'=>$tag,'transportation_mode_name'=>$transportation_mode_name]);
        if(!isset($insert_id)){
            // db::rollback();// 回调
            return ['type' => 'fail', 'msg' => '新增补货任务失败'];
        }

        $request_link = '/amazon_buhuo_data?id=' . $insert_id;
        // $box_code = $this->Addbox($insert_id,$warehouse);//新增任务中转箱

        $request_total_num = 0;
        foreach ($data as $val) {
            //新增详情
            $insert_detail = DB::table('amazon_buhuo_detail')->insert(
                [
                    'request_id' => $insert_id,
                    'sku' => $val['sku'],
                    'request_num' => $val['out_num'],
                    'spu_id'=>$val['spu_id'],
                    'custom_sku_id'=>$val['custom_sku_id'],
                    'create_time' => $create_time,
                    'custom_sku' => $val['custom_sku'],
                    'sku_id'=>$val['sku_id'],
                    'user_id'=>$user_id,
                    'spu' => $val['spu'],
                    'order_id'=>$val['order_id'],
                    'shop_id' => $shop_id,
                    'supplier_id'=>$supplier_id,
                    'transportation_mode_name' => $params['transportation_mode_name'],
                ]);
            if (!$insert_detail) {
                // db::rollback();// 回调
                return ['type' => 'fail', 'msg' => '新增补货明细失败！--'.$val['sku']];
            }

            //新增清单
            $insert_goods_detail = DB::table('goods_transfers_detail')->insert([
                'order_no'=> $insert_id,
                'spu'=>$val['spu'],
                'custom_sku'=>$val['custom_sku'],
                'transfers_num'=>$val['out_num'],
                'createtime'=>$request_time,
                'spu_id'=>$val['spu_id'],
                'custom_sku_id'=>$val['custom_sku_id']
            ]);
            if(!$insert_goods_detail){
                // db::rollback();// 回调
                return ['type' => 'fail', 'msg' => '新增清单明细失败！--'.$val['sku']];
            }

            $request_total_num+=$val['out_num'];
        }
        DB::table('amazon_buhuo_request')->where('id', '=', $insert_id)->update(['request_link' => $request_link]);
        //仓储改动
        $insert_goods_transfers = DB::table('goods_transfers')->insert(
            [
                'order_no'=>$insert_id,
                'user_id'=>$user_id,
                'createtime'=>$request_time,
                'total_num'=>$request_total_num,
                'out_house'=>$warehouse,
                'in_house'=>20,//亚马逊海外仓
                'is_push'=>2,
                'type'=>2,
                'type_detail'=>6,
                'shop_id'=>$shop_id,
                'platform_id'=>5,
            ]);
        if(!$insert_goods_transfers){
            // db::rollback();// 回调
            return ['type' => 'fail', 'msg' => '新增清单失败'];
        }


        //生成任务

        $addtask['task_t_id'] = 18540;
        $addtask['user_fz'] = $user_fz;
        $addtask['user_sh'] = $user_sh;
        $addtask['user_cj'] = $user_id;
        $addtask['request_id'] = $insert_id;
        $addtask['link'] =  $request_link;
        $addtask['start_time'] = $start_time;
        $addtask['end_time'] = $end_time;

        $return['order_id'] = $this->create_task($addtask);
        
        if($return['order_id']>0){
            DB::table('amazon_buhuo_request')->where('id', '=',$insert_id)->update(['request_status' => 3]);
        }
        $return['name'] ='';
        $task = db::table('tasks')->where('id',$return['order_id'])->first();
        if($task){
            $return['name'] = $task->name;
        }



        $autobox =  $this->FactoryautoBox(['request_id'=>$insert_id]);

        if($autobox['type']=='fail'){
            return ['type'=>'fail','msg'=> $autobox['msg']];
        }

        $autobox_detial = $this->FactoryInsertBoxDetail(['request_id'=>$insert_id]);

        if($autobox_detial['type']=='fail'){
            return ['type'=>'fail','msg'=> $autobox['msg']];
        }

        return ['type'=>'success','request_id'=>$insert_id,'task_id'=>$return['order_id']];

     }




     //直发仓补货装箱修改日志
     public function GetFactoryautoBoxLog($params){
        $limit = $params['limit'] ?? 30;
        $page = $params['page'] ?? 1;
        $pageNum = $limit*($page-1);

        $request_id = $params['request_id'];



        $list = db::table('amazon_buhuo_box_log')->where('request_id',$request_id);
        if(isset($params['box_no'])){
            $list = $list->where('box_no',$params['box_no']);
        }
        if(isset($params['sku_id'])){
            $list = $list->where('sku_id',$params['sku_id']);
        }

        if(isset($params['type'])){
            $list = $list->where('type',$params['type']);
        }else{
            $list = $list->whereIn('type',[1,2,3,4,5,6]);
        }

        $count =  $list->count();
        
        $list = $list->limit($limit)
        ->offset($pageNum)->orderby('update_time','desc')->get();
        //1修改 2新增 3走船 4到港 5物流  6排柜
        $type_name = ['1'=>'修改装箱数','2'=>'新增装箱数','3'=>'修改走船时间','4'=>'修改到港时间','5'=>'修改物流方式','6'=>'修改排柜号','7'=>'spu修改排柜号','8'=>'计划修改排柜号'];
        foreach ($list as $v) {
            # code...
            $v->user = $this->GetUsers($v->user_id)['account'];
            $v->type_name =  $type_name[$v->type];
            if($v->type==1||$v->type==2){
                $v->value = $v->old_num.'->'.$v->num;
            }

            if($v->type==5){
                if($v->value==1){
                    $v->value = '大柜';
                }else{
                    $v->value = '散货';
                }
            }

            $v->spu = '';
            if($v->spu_id>0){
                $v->spu = $this->GetSpu($v->spu_id);
            }

        }
        return ['type'=>'success','data'=>$list,'msg'=>'查询成功','totalNum'=> $count];
     }



     public function FactoryautoBox($params){
        $request_id = $params['request_id'];

        db::table('amazon_buhuo_detail')->where('request_id',$request_id)->update(['box_data_detail'=>'','cus_box_id'=> '']);
        db::table('amazon_box_data')->where('request_id',$request_id)->delete();

        $data = db::table('amazon_buhuo_detail')->where('request_id',$request_id)->get();
        $num_js = [];
        $box_ids = [];
        $i = 1;
        foreach ($data as $v) {
            # code...
            $request_num = $v->request_num;
            $sku_id = $v->sku_id;
            $box = db::table('self_custom_sku_box')->where('suppliers_id',$v->supplier_id)->where('custom_sku_id',$v->custom_sku_id)->first();
            if(!$box){
                return ['type'=>'fail','msg'=>'无此箱规,供应商id:'.$v->supplier_id.'--库存skuid:'.$v->custom_sku_id];
            }
            $box_ids[$v->custom_sku_id] = $box->id;
            // $weight = 21.5-$box->box_weight;
            
            // $product_weight_total = $box->num*$box->product_weight;

            $box_num = $box->num;
            //如果数量重量超过箱重，则去最大数量
            // if($product_weight_total>$weight){
            // $box_num = ceil($weight/$box->product_weight);
            // }

            do {
                # code...
                $a = false;
                if($box_num<=$request_num){
                    $num = $box_num;
                    $a = true;
                    $request_num-=$num;

                    $num_js[$sku_id][$i] = $num;
                    
                    $heavy =round($num*$box->product_weight+$box->box_weight,2);


                    db::table('amazon_box_data')->insert(['request_id'=>$request_id,'box_id'=>$i,'box_num'=> $num,'Long'=>$box->box_size_length,'wide'=>$box->box_size_wide,'high'=>$box->box_size_hight,'heavy'=>$heavy]);

                    $i++;
                }
                // }else{
                //     $num = $request_num;
                //     $num_js[$sku_id][$i] = $num;
                    
                //     $heavy =round($num*$box->product_weight+$box->box_weight,2);


                //     db::table('amazon_box_data')->insert(['request_id'=>$request_id,'box_id'=>$i,'box_num'=> $num,'Long'=>$box->box_size_length,'wide'=>$box->box_size_wide,'high'=>$box->box_size_hight,'heavy'=>$heavy]);

                //     $i++;
                // }
        
            } while ($a);



        }


          // var_dump($i);
          foreach ($data as $vs) {
            # code...
            $sku_id = $vs->sku_id;
            $custom_sku_id = $vs->custom_sku_id;
            $n_js = [];

            $ki = 0;

            $init_box_detail = [];
            for ($ti=0; $ti < $i; $ti++) { 
                # code...
                $init_box_detail[] = 0;
            }

            $box_detail = json_encode($init_box_detail);

            
            if(isset($num_js[$sku_id])){
                $num_arr = $num_js[$sku_id];
                for ($inu=1; $inu < $i; $inu++) { 
                    # code...
                    $n_js[$ki] = 0;
                    // if(isset($num_arr[$inu])){
                    //     $n_js[$ki] = $num_arr[$inu];
                    // }
                    foreach ($num_arr as $key => $value) {
                        # code...
                        if($key==$inu){
                            $n_js[$ki] = $value;
                        }
                    }
                    $ki++;
                }
                                // var_dump($n_js);
                        
                $td['num'] = $n_js;
                $td['num_arr'] = $num_arr;
                $td['num_js'] = $num_js;
                $td['custom_sku_id'] = $custom_sku_id;
                $box_detail = json_encode($n_js);
            }

            db::table('amazon_buhuo_detail')->where('request_id',$request_id)->where('sku_id',$sku_id)->update(['box_data_detail'=>$box_detail,'cus_box_id'=> $box_ids[$custom_sku_id],'supplier_id'=>$vs->supplier_id]);
            # code...
        }

        return ['type'=>'success','msg'=>'成功'];

  
     }

     //工厂直发仓自动补充余数
     public function FactoryOtherBox($params){
        $request_id = $params['request_id'];
        $detail = db::table('amazon_buhuo_detail')->where('request_id',$request_id)->get();
        $all_num  = 0;
        $data = $params['data'];

        $other_arr = [];
        foreach ($data as $dsv) {
            # code...
            $other_arr[$dsv['sku_id']] = $dsv['num'];
        }
        foreach ($detail as $v) {
            # code...
            $box_ids[] = $v->cus_box_id;
            // $buhuo_num = array_sum(json_decode($v->box_data_detail,true));
            // $v->other_num = $v->request_num - $buhuo_num;
            $v->other_num = 0;
            if(isset($other_arr[$v->sku_id])){
                $v->other_num = $other_arr[$v->sku_id];
            }
           
            $all_num+= $v->other_num;
        }


        $box = db::table('self_custom_sku_box')->whereIn('id',$box_ids)->min('num');

        // $data['detail'] = $detail;
        // $data['box'] = $box;

        $box_num = ceil($all_num/$box);
        $auto_data = [];
        for ($i=0; $i < $box_num; $i++) { 
            # code...
            $auto_data[$i]['num'] = $box;
        }

        $bi = 0;
        # code...
        $auto_datas = [];
        foreach ($detail as $dv) {

            $num = 0;
        
            do {
                if($auto_data[$bi]['num']>0){
                    if($dv->other_num>$auto_data[$bi]['num']){
                        $dv->other_num-=$auto_data[$bi]['num'];
                        $auto_datas_one['box_num'] = $auto_data[$bi]['num'];
                        $auto_data[$bi]['num'] = 0;
                        $auto_datas_one['sku_id'] = $dv->sku_id; 
                        $auto_datas_one['box_no']  = $bi;
                        $auto_datas[] = $auto_datas_one;
                        $bi++;
                    }else{
                        $auto_data[$bi]['num'] -= $dv->other_num;
                        $auto_datas_one['box_num'] = $dv->other_num;
                        $dv->other_num = 0;
                        $auto_datas_one['sku_id'] = $dv->sku_id;
                        $auto_datas_one['box_no']  = $bi;
                        $auto_datas[] = $auto_datas_one;
                    }
                }else{
                    $bi++;
                }

            } while ($dv->other_num>0);
           
        }
    
 
        $auto_box_data = [];
    
        foreach ($auto_datas as $adv) {
            # code...
            $auto_box_data[$adv['box_no']][] = $adv;
        }


        $data = array_values($auto_box_data);



        return ['type'=>'success','msg'=>'成功','data'=>$data];
     }


    //直发仓补货任务-装箱详情
     public function FactoryInsertBoxDetail($params){
        $request_id = $params['request_id'];
        $detail = db::table('amazon_buhuo_detail')->where('request_id',$request_id)->get();

        $i_ids = [];

        // $heavy = [];

        // $heavy_box = [];
        foreach ($detail as $v) {
            # code...
            $box = db::table('self_custom_sku_box')->where('id',$v->cus_box_id)->first();
            $box_data_detail = json_decode($v->box_data_detail,true);

            foreach ($box_data_detail as $i => $num) {
                # code...
               

                if($num>0){
                    $i = $i+1;
                    // if(isset($heavy[$i])){
                    //     $heavy[$i]+=$box->product_weight*$num;
                    // }else{
                    //     $heavy[$i]=$box->product_weight*$num;
                    // }

                    $insert = [];
                    $insert['request_id'] =  $request_id;
                    $insert['box_no'] = $i;
                    $insert['num'] = $num;
                    $insert['custom_sku_id'] = $v->custom_sku_id;
                    $insert['custom_sku'] = $v->custom_sku;
                    $insert['spu_id'] = $v->spu_id;
                    $insert['spu'] = $v->spu;
                    $insert['user_id'] = $v->user_id;
                    $insert['actual_num'] = $num;
                    $insert['long'] = $box->box_size_length;
                    $insert['wide'] = $box->box_size_wide;
                    $insert['high'] = $box->box_size_hight;
                    $insert['heavy'] = $box->box_weight;
                    $insert['created_at'] = date('Y-m-d H:i:s',time());
                    $insert['updated_at'] =  date('Y-m-d H:i:s',time());
                    $insert['cus_box_id'] = $v->cus_box_id;
                    $insert['shop_id'] = $v->shop_id;
                    $insert['sku'] = $v->sku;
                    $insert['sku_id'] = $v->sku_id;
                    $insert['supplier_id'] = $v->supplier_id;
                    $insert['transportation_mode_name'] = $v->transportation_mode_name;   
                    try {
                        //code...
                        $repeat = db::table('amazon_box_data_detail')->where('request_id',$request_id)->where('box_no',$i)->where('sku_id',$v->sku_id)->first();
    
                        if($repeat){
                             db::table('amazon_box_data_detail')->where('id',$repeat->id)->update($insert);
                             $in_id = $repeat->id;
                        }else{
                            $in_id = db::table('amazon_box_data_detail')->insertGetId($insert);
                        }
                        $i_ids[] =  $in_id;
                    } catch (\Throwable $th) {
                        //throw $th;
                        return ['type'=>'fail','msg'=>$th->getLine().$th->getMessage()];
                    }

                }
            }



            // foreach ($heavy as $heavy_no => $heavy_one) {
            //     # code...
            //     $repeat = db::table('amazon_box_data_detail')->where('request_id',$request_id)->where('box_no',$heavy_no)->update('heavy',round($heavy_one+))
            // }

        }

        return ['type'=>'success','data'=>$i_ids];
     }


     //排柜列表
     public function FactoryChestList($params){

        $limit = $params['limit'] ?? 30;
        $page = $params['page'] ?? 1;
        $pageNum = $limit*($page-1);
        $list = db::table('amazon_buhuo_chest_no');
        if(isset($params['chest_no'])){
            $list = $list->where('chest_no',$params['chest_no']);
        }

        if(isset($params['ds'])){
            $list = $list->where('ds',$params['ds']);
        }

        if(isset($params['status'])){
            $list = $list->where('status',$params['status']);
        }

        
        if(isset($params['user_id'])){
            $list = $list->where('user_id',$params['user_id']);
        }

        $count = $list->count();

        $list = $list->limit($limit)->offset($pageNum)->get();

        foreach ($list as $v) {
            # code...
            $v->ds_moon = date('Y-m',strtotime($v->ds));
            $v->user = $this->GetUsers($v->user_id)['account'];
            $v->real_num = 0;
        }

        return ['type'=>'success','data'=>$list,'totalNum'=>$count];
     }


     //修改排柜
     public function FactoryUpdateChest($params){

        $query = [];
        $query['create_time'] = date('Y-m-d H:i:s',time());
        if(isset($params['status'])){
            $query['status'] = $params['status'];
        }

        // if(isset($params['chest_no'])){
        //     $query['chest_no'] = $params['chest_no'];
        // }

        if(isset($params['ds'])){
            $query['ds'] = $params['ds'];
            $ds = date('Y-m',strtotime($params['ds']));

            $is_repeat = db::table('amazon_buhuo_chest_no')->where('ds','like','%'.$ds.'%')->orderby('chest_no','desc')->first();
            if($is_repeat){
                $query['chest_no'] = $is_repeat->chest_no+1;
            }else{
                $query['chest_no'] = 1;
            }
        }else{
            return ['type'=>'fail','msg'=>'请选择日期'];
        }


        if(isset($params['user_id'])){
            $query['user_id'] = $params['user_id'];
        }

        if(isset($params['real_chest_no'])){
            $query['real_chest_no'] = $params['real_chest_no'];
        }

        if(isset($params['real_ds'])){
            $query['real_ds'] = $params['real_ds'];
            $query['status'] = 3;
        }

        if(isset($params['num'])){
            $query['num'] = $params['num'];
        }



        if(isset($params['id'])){
            db::table('amazon_buhuo_chest_no')->where('id',$params['id'])->update($query);
        }else{
            db::table('amazon_buhuo_chest_no')->insert($query);
        }
     

        return ['type'=>'success','msg'=>'操作成功'];
     }

     //删除排柜
     public function FactoryDelChest($params){

        db::table('amazon_buhuo_chest_no')->whereIn('id',$params['id'])->delete();
        return ['type'=>'success','msg'=>'删除成功'];
     }


    

     public function FactoryInsertBoxDetailBySpuList($params){

        $limit = $params['limit'] ?? 30;
        $page = $params['page'] ?? 1;
        $pageNum = $limit*($page-1);

        $list = db::table('amazon_box_data_detail as a')->leftjoin('amazon_buhuo_request as b','a.request_id','=','b.id')->where('b.request_type',2);

        if(isset($params['request_id'])){
            $list = $list->where('a.request_id',$params['request_id']);
        }

        
        if (isset($params['start_time']) && isset($params['end_time'])) {
            $startTime = $params['start_time'].' 00:00:00';
            $endTime   = $params['end_time'].' 23:59:59';
            $list =$list->whereBetween('b.request_time', [$startTime, $endTime]);
        }
        
        if(isset($params['box_no'])){
            $list = $list->where('a.box_no',$params['box_no']);
        }

                
        if(isset($params['sku'])){
            $skus = db::table('self_sku')->where('sku','like','%'.$params['sku'].'%')->orwhere('old_sku','like','%'.$params['old_sku'].'%')->get()->toarray();
            $sku_ids = array_column($skus,'id');
            $list = $list->whereIn('a.sku_id',$sku_ids);
        }


                
        if(isset($params['custom_sku'])){
            $custom_skus = db::table('self_custom_sku')->where('custom_sku','like','%'.$params['custom_sku'].'%')->orwhere('old_custom_sku','like','%'.$params['custom_sku'].'%')->get()->toarray();
            $custom_sku_ids = array_column($custom_skus,'id');
            $list = $list->whereIn('a.custom_sku_id',$custom_sku_ids);
        }

                     
        if(isset($params['spu'])){
            $spus = db::table('self_spu')->where('spu','like','%'.$params['spu'].'%')->orwhere('old_spu','like','%'.$params['spu'].'%')->get()->toarray();
            $spu_ids = array_column($spus,'id');
            $list = $list->whereIn('a.spu_id',$spu_ids);
        }

        if(isset($params['shop_id'])){
            $list = $list->where('a.shop_id',$params['shop_id']);
        }

        $posttype = $params['posttype']??1;

        // $list = $list->groupby('request_id','box_no')->select('a.request_id','a.box_no',db::raw('sum(a.num) as num'),)->get();
        $count = $list->groupby('a.request_id','a.spu_id')->get()->count();
        if($posttype==1){
            $list = $list->groupby('a.request_id','a.spu_id')->orderby('a.request_id','desc')->orderby('a.box_no','asc')->select('a.*',db::raw('group_concat(a.box_no) as box_nos'),db::raw('group_concat(a.chest_id) as chest_ids'),db::raw('sum(a.num) as nums'),'b.tag','b.delivery_date')->limit($limit)
            ->offset($pageNum)->get();
        }else{
            $list = $list->groupby('a.request_id','a.spu_id')->orderby('a.request_id','desc')->orderby('a.box_no','asc')->select('a.*',db::raw('group_concat(a.box_no) as box_nos'),db::raw('group_concat(a.chest_id) as chest_ids'),db::raw('sum(a.num) as nums'),'b.tag','b.delivery_date')->get();
        }



       
   
        foreach ($list as $v) {
            # code...
            $v->box_nos = array_unique(explode(',',$v->box_nos));
            $v->box_noss = implode(',',$v->box_nos);
            $create_goods = db::table('amazon_create_goods')->where('request_id',$v->request_id)->first();
            if($create_goods){
                $fba = $create_goods->serial_no;
            }else{
                $fba = '';
            }
            $v->fba = $fba;
            $v->box_all_num = db::table('amazon_box_data_detail')->where('request_id',$v->request_id)->where('box_no',$v->box_no)->sum('num');
            $v->supplier_no = '';
            $supplier = db::table('suppliers')->where('Id',$v->supplier_id)->first();
            $v->market_name = '';
            if($supplier){
                $v->supplier_no =$supplier->supplier_no;
                $spu = db::table('self_spu')->where('id',$v->spu_id)->first();
                $v->market = $spu->market;
                if($v->market=='E'){
                    $v->market_name = '欧版';
                }elseif($v->market=='U'){
                    $v->market_name = '美版';
                }
            }

            $cus = db::table('self_custom_sku')->where('id',$v->custom_sku_id)->first();
            $v->name = '';
            $v->size = '';
            if($cus){
                $v->name = $cus->name.'+'.$cus->color;
                $v->size = $cus->size;
            }
    
            $v->shop_name = $this->GetShop($v->shop_id)['shop_name']??'';
            $v->brand = '';
            $v->fnsku = '';
            $product = db::table('product_detail')->where('sku_id',$v->sku_id)->first();
            if($product){
                $v->brand =  $product->brand;
                $v->fnsku = $product->fnsku;
            }
            $v->fnsku_link = 'http://8.134.97.20:9998/admin/CodeImg.php?fnsku='.$v->fnsku;

            if($v->logistics_type==1){
                $v->logistics_type_name = '大柜';
            }else{
                $v->logistics_type_name = '散货';
            }

            $chest_ids = explode(',',$v->chest_ids);
            $v->chest_no = [];
            if(count($chest_ids)>0){

                $chest = db::table('amazon_buhuo_chest_no')->whereIn('id',$chest_ids)->get();
                if($chest->isNotEmpty()){
                    $v->chest_no = array_column($chest->toarray(),'chest_no');
                }
                // foreach ($chest_ids as $chest_id) {
                //     $chest = db::table('amazon_buhuo_chest_no')->where('id',$v->chest_id)->first();
                //     if($chest){
                //         $v->chest_no = $chest->chest_no;
                //     }                    # code...
                // }
            }
            $v->chest_nos = implode(',',$v->chest_no);
        }

   

        if($posttype==2){
            $p['title']='工厂直发仓补货详情SPU表'.time();
            $p['title_list']  = [
                'request_id'=>'订单号',
                'spu'=>'spu',
                'box_noss'=>'箱号',
                'chest_nos'=>'排柜号',
                'num'=>'箱数',
            ];

            // $this->excel_expord($p);
            
            $p['data'] =   $list;
            $p['user_id'] =$params['find_user_id']??1;
            $p['type'] = '工厂直发仓补货详情SPU表-导出';
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return $this->FailBack('加入队列失败');
            }
            return ['type'=>'success','msg'=>'加入队列成功'];
        }
        return ['type'=>'success','data'=>$list,'totalNum'=>$count];

     }

     public function FactoryInsertBoxDetailList($params){

        $limit = $params['limit'] ?? 30;
        $page = $params['page'] ?? 1;
        $pageNum = $limit*($page-1);

        $list = db::table('amazon_box_data_detail as a')->leftjoin('amazon_buhuo_request as b','a.request_id','=','b.id')->where('b.request_type',2);

        if(isset($params['request_id'])){
            $list = $list->where('a.request_id',$params['request_id']);
        }

        
        if (isset($params['start_time']) && isset($params['end_time'])) {
            $startTime = $params['start_time'].' 00:00:00';
            $endTime   = $params['end_time'].' 23:59:59';
            $list =$list->whereBetween('b.request_time', [$startTime, $endTime]);
        }
        
        if(isset($params['box_no'])){
            $list = $list->where('a.box_no',$params['box_no']);
        }

                
        if(isset($params['sku'])){
            $skus = db::table('self_sku')->where('sku','like','%'.$params['sku'].'%')->orwhere('old_sku','like','%'.$params['old_sku'].'%')->get()->toarray();
            $sku_ids = array_column($skus,'id');
            $list = $list->whereIn('a.sku_id',$sku_ids);
        }


                
        if(isset($params['custom_sku'])){
            $custom_skus = db::table('self_custom_sku')->where('custom_sku','like','%'.$params['custom_sku'].'%')->orwhere('old_custom_sku','like','%'.$params['custom_sku'].'%')->get()->toarray();
            $custom_sku_ids = array_column($custom_skus,'id');
            $list = $list->whereIn('a.custom_sku_id',$custom_sku_ids);
        }

                     
        if(isset($params['spu'])){
            $spus = db::table('self_spu')->where('spu','like','%'.$params['spu'].'%')->orwhere('old_spu','like','%'.$params['spu'].'%')->get()->toarray();
            $spu_ids = array_column($spus,'id');
            $list = $list->whereIn('a.spu_id',$spu_ids);
        }

        if(isset($params['shop_id'])){
            $list = $list->where('a.shop_id',$params['shop_id']);
        }

        if(isset($params['chest_id'])){
            $list = $list->where('a.chest_id',$params['chest_id']);
        }
        if(isset($params['spu_id'])){
            $list = $list->where('a.spu_id',$params['spu_id']);
        }
        $posttype = $params['posttype']??1;

        // $list = $list->groupby('request_id','box_no')->select('a.request_id','a.box_no',db::raw('sum(a.num) as num'),)->get();
        $count = $list->count();
        if($posttype==1){
            $list = $list->orderby('a.request_id','desc')->orderby('a.box_no','asc')->select('a.*','b.tag','b.delivery_date')->limit($limit)
            ->offset($pageNum)->get();
        }else{
            $list = $list->orderby('a.request_id','desc')->orderby('a.box_no','asc')->select('a.*','b.tag','b.delivery_date')->get();
        }



       
   
        foreach ($list as $v) {
            # code...
            $create_goods = db::table('amazon_create_goods')->where('request_id',$v->request_id)->first();
            if($create_goods){
                $fba = $create_goods->serial_no;
            }else{
                $fba = '';
            }
            $v->fba = $fba;
            $v->box_all_num = db::table('amazon_box_data_detail')->where('request_id',$v->request_id)->where('box_no',$v->box_no)->sum('num');
            $v->supplier_no = '';
            $supplier = db::table('suppliers')->where('Id',$v->supplier_id)->first();
            $v->market_name = '';
            if($supplier){
                $v->supplier_no =$supplier->supplier_no;
                $spu = db::table('self_spu')->where('id',$v->spu_id)->first();
                $v->market = $spu->market;
                if($v->market=='E'){
                    $v->market_name = '欧版';
                }elseif($v->market=='U'){
                    $v->market_name = '美版';
                }
            }

            $cus = db::table('self_custom_sku')->where('id',$v->custom_sku_id)->first();
            $v->name = '';
            $v->size = '';
            if($cus){
                $v->name = $cus->name.'+'.$cus->color;
                $v->size = $cus->size;
            }
    
            $v->shop_name = $this->GetShop($v->shop_id)['shop_name']??'';
            $v->brand = '';
            $v->fnsku = '';
            $product = db::table('product_detail')->where('sku_id',$v->sku_id)->first();
            if($product){
                $v->brand =  $product->brand;
                $v->fnsku = $product->fnsku;
            }
            $v->fnsku_link = 'http://8.134.97.20:9998/admin/CodeImg.php?fnsku='.$v->fnsku;

            if($v->logistics_type==1){
                $v->logistics_type_name = '大柜';
            }else{
                $v->logistics_type_name = '散货';
            }

            $v->chest_no = '';
            $chest = db::table('amazon_buhuo_chest_no')->where('id',$v->chest_id)->first();
            if($chest){
                $v->chest_no = $chest->chest_no;
            }
        }

   

        if($posttype==2){
            $p['title']='工厂直发仓补货详情表'.time();
            $p['title_list']  = [
                'request_id'=>'订单号',
                'box_no'=>'箱号',
                'chest_no'=>'排柜号',
                'custom_sku'=>'库存sku',
                'sku'=>'渠道sku',
                'fba'=>'fba',
                'fnsku'=>'fnsku',
                'fnsku_link'=>'FNSKU链接',
                'logistics_type_name'=>'物流方式',
                'transportation_mode_name'=>'运输方式',
                'market_name'=>'版型',
                'name'=>'中文名+颜色',
                'size'=>'尺码',
                'shop_name'=>'店铺',
                'num'=>'箱数',
                'box_all_num'=>'总数量',
                'long'=>'箱规-长',
                'wide'=>'箱规-宽',
                'high'=>'箱规-高',
                'heavy'=>'每箱毛重',
                'delivery_date'=>'最晚发货时间',
                'runboat_time'=>'走船时间',
                'arrival_time'=>'到港时间',
            ];

            // $this->excel_expord($p);
            
            $p['data'] =   $list;
            $p['user_id'] =$params['find_user_id']??1;
            $p['type'] = '工厂直发仓补货详情表-导出';
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return $this->FailBack('加入队列失败');
            }
            return ['type'=>'success','msg'=>'加入队列成功'];
        }
        return ['type'=>'success','data'=>$list,'totalNum'=>$count];

     }
     public function UpdateFactoryBoxDetail($params){

        $data = $params['data'];
        db::beginTransaction();    //开启事务
        foreach ($data as $v) {
            # code...
            //1修改 2新增 3走船 4到港 5物流  6排柜
            if(isset($params['runboat_time'])){
                $v['runboat_time'] = $params['runboat_time'];
            
            }
            if(isset($params['arrival_time'])){
                $v['arrival_time'] = $params['arrival_time'];
            }
            if(isset($params['logistics_type'])){
                $v['logistics_type'] = $params['logistics_type'];
            }

            if(isset($params['chest_id'])){
                $v['chest_id'] = $params['chest_id'];
            }

            if(isset($params['num'])){
                $v['num'] = $params['num'];
            }

            $v['user_id'] = $params['user_id'];
            try {
               $rt =  $this->UpdateFactoryBoxDetailone($v);
               if($rt['type']=='fail'){
                db::rollback();// 回调
                return ['type'=>'fail','msg'=>$rt['msg']];
               }
                //code...
            } catch (\Throwable $th) {
                //throw $th;
                db::rollback();// 回调
                return ['type'=>'fail','msg'=>$th->getLine().'-'.$th->getMessage()];
            }

        }

        db::commit();

        return ['type'=>'success'];

     }


     public function UpdateFactoryBoxDetailSpus($params){
        $user_id = $params['user_id'];
        $chest_id = $params['chest_id'];
        $data = $params['data'];

        foreach ($data as $v) {
            # code...
            $detail = db::table('amazon_box_data_detail')->where('request_id',$v['request_id'])->where('spu_id',$v['spu_id'])->get()->toarray();
            $box_no = array_unique(array_column($detail,'box_no'));
            $v['box_no'] =  $box_no;
            $v['user_id'] = $user_id;
            $v['chest_id'] = $chest_id;
            // var_dump($v);
            $r =  $this->UpdateFactoryBoxDetailSpu($v);
            if($r['type']=='fail'){
                return  $r;
            }
        }

        return ['type'=>'success','msg'=>'修改成功'];
     }

     public function UpdateFactoryBoxDetailRequest($params){
        $request_id = $params['request_id'];
        $chest_id =  $params['chest_id'];
        $user_id =  $params['user_id'];
        $now_num = db::table('amazon_box_data_detail')->where('chest_id', $chest_id)->sum('num');
        $chest = db::table('amazon_buhuo_chest_no')->where('id',$chest_id)->first();
        if(!$chest){
            return ['type'=>'fail','msg'=>'无此柜号'];
        }
        $add_num= db::table('amazon_box_data_detail')->where('request_id',$request_id)->sum('num');
        $now_num+=$add_num;
        // if($now_num>$chest->num){
        //     return ['type'=>'fail','msg'=>'计划id'.$request_id.'装柜数大于最大装柜数'.$chest->ds.'-'.$chest->chest_no.'可装箱：'.$chest->num.'-已装箱：'. $now_num];
        // }

        $msg = '计划：'.$request_id.'更改柜号为->'.$chest->chest_no;

        db::table('amazon_buhuo_chest_no')->where('id', $params['chest_id'])->update(['status'=>2]);
        //加入日志
        db::table('amazon_buhuo_box_log')->insert(['request_id'=>$request_id,'box_no'=>0,'user_id'=>$user_id,'spu_id'=>0,'update_time'=>date('Y-m-d H:i:s',time()),'type'=>8,'value'=>$msg]);
        db::table('amazon_box_data_detail')->where('request_id',$request_id)->update(['chest_id'=>$chest_id]);

        return ['type'=>'success','msg'=>'修改成功'];
     }

     //spu级别排柜
     public function UpdateFactoryBoxDetailSpu($params){
            $request_id = $params['request_id'];
            $spu_id = $params['spu_id'];
            $user_id = $params['user_id'];
            $box_no = $params['box_no'];
          
            //runboat_time  arrival_time logistics_type chest_no
            $d_update['chest_id'] = $params['chest_id'];

            $now_num = db::table('amazon_box_data_detail')->where('chest_id', $params['chest_id'])->sum('num');
            $chest = db::table('amazon_buhuo_chest_no')->where('id',$params['chest_id'])->first();
            if(!$chest){
                return ['type'=>'fail','msg'=>'无此柜号'];
            }


      
            $add_num= db::table('amazon_box_data_detail')->where('request_id',$request_id)->where('spu_id',$spu_id)->whereIn('box_no',$box_no)->sum('num');
            $now_num+=$add_num;
            // if($now_num>$chest->num){
            //     return ['type'=>'fail','msg'=>'计划id'.$request_id.'装柜数大于最大装柜数'.$chest->ds.'-'.$chest->chest_no.'可装箱：'.$chest->num.'-已装箱：'. $now_num];
            // }

            db::table('amazon_buhuo_chest_no')->where('id', $params['chest_id'])->update(['status'=>2]);

            $msg = '【'.implode(',',$box_no).'箱】更改柜号为->'.$chest->chest_no;
            //加入日志
            db::table('amazon_buhuo_box_log')->insert(['request_id'=>$request_id,'box_no'=>0,'user_id'=>$user_id,'spu_id'=>$spu_id,'update_time'=>date('Y-m-d H:i:s',time()),'type'=>7,'value'=>$msg]);
            db::table('amazon_box_data_detail')->where('request_id',$request_id)->where('spu_id',$spu_id)->whereIn('box_no',$box_no)->update($d_update);
            return ['type'=>'success','msg'=>'修改成功'];
    
     }
     public function UpdateFactoryBoxDetailone($params){
        $request_id = $params['request_id'];
        $sku_id = $params['sku_id'];
        $box_no = $params['box_no'];
        $user_id = $params['user_id'];

        $detail = db::table('amazon_buhuo_detail')->where('request_id',$request_id)->where('sku_id',$sku_id)->first();
        if(isset($params['num'])){
            $num = $params['num'];
            // $detail = db::table('amazon_buhuo_detail')->where('request_id',$request_id)->where('sku_id',$sku_id)->first();
            $box_data_detail = json_decode($detail->box_data_detail,true);
    
            // $new_box_data = [];
            $old_num = 0;
            $i = 1;
            foreach ($box_data_detail as &$v) {
                # code...
                if($box_no==$i){
                    $old_num  = $v;
                    $v=$num;
                }
    
                $i++;
            }
    
    
            db::table('amazon_buhuo_detail')->where('id',$detail->id)->update(['box_data_detail'=>json_encode($box_data_detail)]);
            $d_update['num'] = $num;
            $d_update['actual_num']=$num;
            //加入日志
            db::table('amazon_buhuo_box_log')->insert(['request_id'=>$request_id,'box_no'=>$box_no,'num'=>$num ,'user_id'=>$user_id,'sku_id'=>$detail->sku_id,'update_time'=>date('Y-m-d H:i:s',time()),'old_num'=> $old_num,'type'=>2,'sku'=>$detail->sku]);
        }

      


 



        //1修改 2新增 3走船 4到港 5物流  6排柜
        if(isset($params['runboat_time'])){
            //runboat_time  arrival_time logistics_type chest_no
            $d_update['runboat_time'] = $params['runboat_time'];
            $chestid =  db::table('amazon_box_data_detail')->where('request_id',$request_id)->where('sku_id',$sku_id)->where('box_no',$box_no)->first()->chest_id;
            if($chestid>0){
                db::table('amazon_buhuo_chest_no')->where('id', $chestid)->update(['status'=>4]);
            }else{
                return ['type'=>'fail','msg'=>$request_id.'sku_id'.$sku_id.'-该sku未排柜，无法回填走船时间'];
            }

            //加入日志
            db::table('amazon_buhuo_box_log')->insert(['request_id'=>$request_id,'box_no'=>$box_no,'user_id'=>$user_id,'sku_id'=>$detail->sku_id,'update_time'=>date('Y-m-d H:i:s',time()),'type'=>3,'sku'=>$detail->sku,'value'=>$params['runboat_time']]);
        }
        if(isset($params['arrival_time'])){
            //runboat_time  arrival_time logistics_type chest_no
            $d_update['arrival_time'] = $params['arrival_time'];
            //加入日志
            db::table('amazon_buhuo_box_log')->insert(['request_id'=>$request_id,'box_no'=>$box_no,'user_id'=>$user_id,'sku_id'=>$detail->sku_id,'update_time'=>date('Y-m-d H:i:s',time()),'type'=>4,'sku'=>$detail->sku,'value'=>$params['arrival_time']]);
        }
        if(isset($params['logistics_type'])){
            //runboat_time  arrival_time logistics_type chest_no
            $d_update['logistics_type'] = $params['logistics_type'];
            //加入日志
            db::table('amazon_buhuo_box_log')->insert(['request_id'=>$request_id,'box_no'=>$box_no,'user_id'=>$user_id,'sku_id'=>$detail->sku_id,'update_time'=>date('Y-m-d H:i:s',time()),'type'=>5,'sku'=>$detail->sku,'value'=>$params['logistics_type']]);
        }

        if(isset($params['chest_id'])){
            //runboat_time  arrival_time logistics_type chest_no
            $d_update['chest_id'] = $params['chest_id'];

            $now_num = db::table('amazon_box_data_detail')->where('chest_id', $params['chest_id'])->sum('num');
            $chest = db::table('amazon_buhuo_chest_no')->where('id',$params['chest_id'])->first();
            if(!$chest){
                return ['type'=>'fail','msg'=>'无此柜号'];
            }
            if(isset($params['num'])){
                $add_num = $params['num'];
            }else{
                $add= db::table('amazon_box_data_detail')->where('request_id',$request_id)->where('sku_id',$sku_id)->where('box_no',$box_no)->first();
                $add_num =$add->num;
            }
            $now_num+=$add_num;
            // if($now_num>$chest->num){
            //     return ['type'=>'fail','msg'=>'装柜数大于最大装柜数'.$chest->num.'-'. $now_num];
            // }

            db::table('amazon_buhuo_chest_no')->where('id', $params['chest_id'])->update(['status'=>2]);
            //加入日志
            db::table('amazon_buhuo_box_log')->insert(['request_id'=>$request_id,'box_no'=>$box_no,'user_id'=>$user_id,'sku_id'=>$detail->sku_id,'update_time'=>date('Y-m-d H:i:s',time()),'type'=>6,'sku'=>$detail->sku,'value'=>$params['chest_id']]);
        }



        db::table('amazon_box_data_detail')->where('request_id',$request_id)->where('sku_id',$sku_id)->where('box_no',$box_no)->update($d_update);


        return ['type'=>'success'];
     }
     //工厂直发计划合并导出
     public function FactoryPlanExport($params){

        $order_no = $params['order_no'];

        $list = db::table('amazon_buhuo_detail')->whereIn('request_id',$order_no)->get();
        $request = db::table('amazon_buhuo_request')->where('id',$order_no)->first();
        $create_goods = db::table('amazon_create_goods')->whereIn('request_id',$order_no)->get();
        $re_no = [];
        foreach ($create_goods as $v) {
            # code...
            $re_no[$v->request_id] = $v->serial_no;
        }




        $new_list = [];
        foreach ($list as $v) {
            # code...
            $v->delivery_date = $request->delivery_date;
            $v->supplier_no = '';
            $supplier = db::table('suppliers')->where('Id',$v->supplier_id)->first();
            if($supplier){
                $v->supplier_no =$supplier->supplier_no;
            }
            $boxs = db::table('self_custom_sku_box')->where('id',$v->cus_box_id)->first();
            $cus = db::table('self_custom_sku')->where('id',$v->custom_sku_id)->first();
            $spu = db::table('self_spu')->where('id',$cus->spu_id)->first();
            $v->market = $spu->market;

            $v->market_name = '';

            if($v->market=='E'){
                $v->market_name = '欧版';
            }elseif($v->market=='U'){
                $v->market_name = '美版';
            }
            $v->name = '';
            $v->size = '';
            if($cus){
                $v->name = $cus->name.'+'.$cus->color;
                $v->size = $cus->size;
            }
    
            $v->shop_name = $this->GetShop($v->shop_id)['shop_name']??'';
            $v->brand = '';
            $v->fnsku = '';
            $product = db::table('product_detail')->where('sku_id',$v->sku_id)->first();
            if($product){
                $v->brand =  $product->brand;
                $v->fnsku = $product->fnsku;
            }
            $v->fnsku_link = 'http://8.134.97.20:9998/admin/CodeImg.php?fnsku='.$v->fnsku;

            $v->factory_box_no = 0;

            $v->box_weight = $boxs->box_weight;
            $v->box_size = $boxs->box_size;
            $v->box_num = 1;
            $box_data_detail = json_decode($v->box_data_detail,true);
            foreach ($box_data_detail as $box_no => $num) {
                # code...
                if($num>0){
                    $v->box_no = $box_no+1;
                    $v->total_num = $num;
                    $v->one_box_num = $num;
                    $new_list_a['fba'] = '';
                    $new_list_a['request_id'] = $v->request_id;
                    if(isset($re_no[$v->request_id])){
                        $new_list_a['fba'] = $re_no[$v->request_id];
                    }
                    $new_list_a['custom_sku'] = $v->custom_sku;
                    $new_list_a['sku'] = $v->sku;
                    $new_list_a['name'] = $v->name;
                    $new_list_a['shop_name'] = $v->shop_name;
                    $new_list_a['brand'] = $v->brand;
                    $new_list_a['size'] = $v->size;
                    $new_list_a['fnsku'] = $v->fnsku;
                    $new_list_a['fnsku_link'] = $v->fnsku_link;
                    $new_list_a['total_num'] = $v->total_num;
                    $new_list_a['one_box_num'] = $v->one_box_num;
                    $new_list_a['factory_box_no'] = $v->factory_box_no;
                    $new_list_a['box_no'] = $v->box_no;
                    $new_list_a['box_num'] = $v->box_num;
                    $new_list_a['box_weight'] = $v->box_weight;
                    $new_list_a['box_size'] = $v->box_size;

                    $new_list_a['supplier_no'] = $v->supplier_no;
                    $new_list_a['market_name'] = $v->market_name;
                    $new_list_a['delivery_date'] = $v->delivery_date;

                    $new_list[] = $new_list_a;

                }

            }
       
        }



        $posttype = $params['posttype']??1;
        if($posttype==2){
            $p['title']='工厂直发计划合并导出'.time();
            $p['title_list'] = [
                'request_id'=>'订单',
                'custom_sku'=>'库存sku',
                'sku' => '渠道sku',
                'market_name'=>'版型',
                'name' => '中文名+颜色',
                'shop_name'=>'店铺',
                'brand'=>'吊牌',
                'size'=>'尺码',
                'fnsku'=>'FNSKU',
                'fnsku_link'=>'FNSKU链接',
                'total_num'=>'总数量',
                'one_box_num'=>'单箱数量',
                'factory_box_no'=>'工厂箱号',
                'box_no'=>'我司箱号',
                'box_num'=>'箱数',
                'box_weight'=>'每箱毛重',
                'box_size'=>'箱规',
                'fba'=>'FBA信息',
                'delivery_date'=>'最晚发货时间',
                'supplier_no'=>'供应商代号',
            ];

            $p['data'] =   $new_list;
            $p['user_id'] =  $params['find_user_id']??1;  
            $p['type'] = '工厂直发计划合并导出-导出';
            // var_dump($p);
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }

     }



      //工厂补货导入
    public function Importfactory($params){
        $p['row'] = ['sku','request_num'];
        $p['file'] = $params['file'];
        $p['start'] = 2;
        $data =  $this->CommonExcelImport($p);

        $sku_ids = [];
        $request_num = [];
        $shop_id = 0;
        $err = [];

        $import_sku = [];
        foreach ($data as $v) {
            # code...
            if($v['request_num']>0){
                if(!empty($v['sku'])){
                    $sku_id= db::table('self_sku')->where('sku',$v['sku'])->orwhere('old_sku',$v['sku'])->first();
                    if($sku_id){
                            $import_sku[$sku_id->id] = $v['sku'];
                            $sku_ids[] = $sku_id->id;
                            $request_num[$sku_id->id] = $v['request_num'];
                            if($shop_id==0){
                                $shop_id = $sku_id->shop_id;
                            }else{
                                if($shop_id!=$sku_id->shop_id){
                                    return ['type'=>'fail','msg'=>'请导入相同店铺sku'.$v['sku']];
                                }
                            }
                    }else{
                        $err[] = $v['sku'];
                    }
                }
            }
        
        }

        if(count($err)>0){
            return ['type'=>'fail','msg'=>'无此sku，请在系统绑定后再发货'.implode(',',$err)];
        }

        try {
            //code...
           $data = $this->getFactoryBuhuo(['sku_ids'=>$sku_ids,'request_num'=>$request_num,'limit'=>count($sku_ids)+1]);
        } catch (\Throwable $th) {
            return ['type'=>'fail','msg'=>$th->getMessage()];
        }

        $r_err = [];
        $check_sku = [];
        foreach ($data['data'] as $dv) {
            # code...
            if($dv->request_num>$dv->num){
                $r_err[] = $dv->sku.'('.$dv->old_sku.')--补货数：'.$dv->request_num.'最大可补'.$dv->num.'已发布计划id'.$dv->request_ids."<br>";
            }else{
                $check_sku[$dv->sku_id] = 1;
            }
        }

        $c_err = [];
        foreach ($import_sku as $i_sku_id => $i_sku) {
            # code...
            if(!isset($check_sku[$i_sku_id])){
                $c_err[] = $i_sku;
            }
        }

        if(count($r_err)>0){
            return ['type'=>'fail','msg'=>'补货数量超出最大补货数'."<br>".implode(',',$r_err)];
        }

        if(count($c_err)>0){
            return ['type'=>'fail','msg'=>'以下sku没有下单数据无法补货'."<br>".implode(',',$c_err)];
        }
      
        return ['msg'=>'导入成功','type'=>'success','data'=>$data['data']];
    }



    // /**
    //  * @Desc:校验商品库存
    //  * @param $warehouse
    //  * @param $data
    //  * @return mixed
    //  * @author: Liu Sinian
    //  * @Time: 2023/2/24 9:57
    //  */
//    private function _judgeInventory($warehouse, $data)
//    {
//        try {
//            $warehouseId = [];
//            if (!in_array($warehouse, [1, 2, 3])) {
//                throw new \Exception('仓库非预设值');
//            }
//            foreach ($data as $item) {
//                // 计划补货数量合计
//                $planNum = $item['shipping_num'] + $item['air_num'] + $item['courier_num'];
//                // 获取库存sku详情
//                $customSku = $item['custom_sku'];
//                $customSkuModel = new CustomSkuModel();
//                $customSkuData = $customSkuModel::query()
//                    ->where('custom_sku', $item['custom_sku'])
//                    ->orWhere('old_custom_sku', $item['custom_sku'])
//                    ->first();
//                if (empty($customSkuData)) {
//                    throw new \Exception('库存SKU不存在！');
//                }
//               if($customSkuData->type == 2){    // 组合sku
//                    // 获取组合库存sku绑定的库存sku
//                    $groupCustomSkuModel = new GroupCustomSkuModel();
//                    $groupCustomSkuData = $groupCustomSkuModel::query()
//                        ->where('custom_sku_id', $customSkuData->id)
//                        ->get();
//                    // 判断是否有绑定数据
//                    if (empty($groupCustomSkuData)){
//                        throw new \Exception("补货计划创建失败！组合库存SKU:".$customSkuData->custom_sku."未查询到绑定的库存sku！");
//                    }
//                    // 遍历查找库存sku的库存数据
//                    foreach ($groupCustomSkuData as $group){
//                        $stock = $this->getBuhuoByCus($customSkuData->group_custom_sku);
//                        // 判断是否云仓仓库
//                        if ($warehouse == 1){
//                            if ($stock['tongAn_deduct_inventory'] < $planNum){
//                                throw new \Exception("补货计划创建失败！组合库存SKU:".$customSkuData->custom_sku."同安仓库库存不足！");
//                            }
//                        }
//                        if ($warehouse == 2){
//                            if ($stock['quanzhou_deduct_inventory'] < $planNum){
//                                throw new \Exception("补货计划创建失败！组合库存SKU:".$customSkuData->custom_sku."泉州仓库库存不足！");
//                            }
//                        }
//                        if ($warehouse == 3){
//                            // 校验预减后库存是否足够
//                            if ($stock['cloud_deduct_inventory'] < $planNum){
//                                throw new \Exception("补货计划创建失败！组合库存SKU:".$customSkuData->custom_sku."云仓仓库库存不足！");
//                            }
//                        }
//                    }
//                }else{
//                    throw new \Exception('库存SKU类型错误！');
//                }
//            }
//        } catch (\Exception $e) {
//            return ['code' => 500, 'msg' => $e->getMessage()];
//        }
//
//        return ['code' => 200];
//    }


    //生产理货标签
    public function SendLhLabel($params){
        $request_id = $params['request_id'];
        $data = db::table('amazon_create_goods')->where('request_id',$request_id)->first();
        if(!$data){
            return ['code' => 500, 'msg' => '无此任务'.$request_id];
        }

        $box_num = count(explode(',',$data->box_ids));

        $buhuo_request = db::table('amazon_buhuo_request')->where('id',$request_id)->first();
        if(!$buhuo_request){
            return ['code' => 500, 'msg' => '无此补货任务'.$request_id];
        }
        $type = $buhuo_request->request_type;
        $shops = db::table('shop')->where('Id',$data->shop_id)->first();
        if($shops->region=='NA'){
            $types = 1;
        }elseif($shops->region=='EU'){
            $types = 2;
        }else{
            return ['code' => 500, 'msg' => '该店铺非美国欧洲'.$shops->region];
        }

        $is_r =  db::table('amazon_create_goods_log') ->where('request_id',$request_id)->first();
        if($is_r){
            $no = $is_r->no;
        }else{
            $no = db::table('amazon_create_goods_log')->where('type',$types)->orderby('id','desc')->first()->no;
            $no++;
            db::table('amazon_create_goods_log')->insertGetId(['type'=>$types,'request_id'=>$request_id,'box_num'=>$box_num,'no'=>$no]);
        }

        $no = str_pad($no, 3, '0',STR_PAD_LEFT);

        $return['laber'] = $data->DestinationFulfillmentCenterId;
        $return['no'] = $no;
        $return['types'] = $types;
        $return['box_num'] = $box_num;
        $return['request_id'] = $request_id;
        return ['code' => 200,'data'=>$return];
    }

    //获取亚马逊补货单数据
    public function select_buhuoDoc($params)
    {

        $where = "1=1";
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $page = $this->getLimitParam($page, $limit);
//        var_dump($page);die;
        if (!empty($params['store_id'])) {
            $where .= " and a.shop_id={$params['store_id']}";
        }
        if (!empty($params['user_id'])) {
            $where .= " and a.request_userid={$params['user_id']}";
        }
        if (!empty($params['status_id'])) {
            $status_id = implode(',',$params['status_id']);
            $where .= " and a.request_status in ($status_id)";
        }
        if (!empty($params['plan_id'])) {
            $where .= " and a.id in ({$params['plan_id']})";
        }
        if (!empty($params['id'])) {
            $id = implode(',', $params['id']);
            $where .= " and a.id in ({$id})";
        }
        if (!empty($params['warehouse'])) {
            $where .= " and a.warehouse={$params['warehouse']}";
        }

        if (isset($params['request_time'][0])) {
            $time_start = $params['request_time'][0] . ' 00:00:00';
            $time_end = $params['request_time'][1] . ' 23:59:59';
            $where .= " and a.request_time between '{$time_start}' and '{$time_end}'";
        }

        if (!empty($params['custom_sku'])) {
            $where .= " and (c.sku like '%{$params['custom_sku']}%' or c.custom_sku like '%{$params['custom_sku']}%')";
        }

        if (isset($params['shipping_type'])) {
            $shipping_type = implode('\',\'', $params['shipping_type']);
            $where .= " and a.transportation_mode_name in ('{$shipping_type}')";
        }

        if (isset($params['fid'])) {
            $where .= " and a.fid={$params['fid']}";
        }

        if (isset($params['is_publish_fba'])) {
            $where .= " and a.is_publish_fba={$params['is_publish_fba']}";
        }

        if (isset($params['request_id'])){
            $re = db::table('amazon_buhuo_request')
                ->where('id', $params['request_id'])
                ->first();
            $id = $params['request_id'];
            if (!empty($re->fid)){
                $id = $re->fid;
            }
            $where .= " and a.id={$id}";
        }

        $where .= " and a.fid = 0";

        $sql = "SELECT  SQL_CALC_FOUND_ROWS
                    DISTINCT(a.id),                   
                    a.request_link,
                    a.request_time,
                    a.delivery_date,
                    a.update_time,  
                    a.request_status,
                    a.update_user,  
                    a.calculate_heavy,
                    a.logistics_price,                   
                    a.request_userid,
                    a.request_status,
                    a.shop_id,
                    a.tag,
                    b.file_name,
                    b.file_path,        
                    b.serial_no,
                    b.tracking_no,
                    b.shipping_address,
                    b.DestinationFulfillmentCenterId,
                    a.warehouse,
                    b.box_ids,
                    a.transportation_mode_name,
                    a.transportation_date,
                    c.transportation_type,
                    a.request_type,
                    a.runboat_time,
                    a.arrival_time,
                    c.supplier_id,
                    a.arrival_time,
                    a.is_publish_fba
                FROM
                    amazon_buhuo_request a
                LEFT JOIN amazon_create_goods b ON a.id = b.request_id
                LEFT JOIN amazon_buhuo_detail c ON a.id = c.request_id
                WHERE
                    $where
                GROUP BY a.id
                ORDER BY
                    a.request_time desc LIMIT $page,$limit";

        $data = DB::select($sql);

        $totalNum = db::select("SELECT FOUND_ROWS() as total")[0]->total;
        $shops = DB::table('shop')->where('platform_id', 5)->select('Id', 'shop_name')->get();
        $shops = json_decode(json_encode($shops), true);
        $shop_arr = array();
        foreach ($shops as $s) {
            $shop_arr[$s['Id']] = $s['shop_name'];
        }
        $users = DB::table('users')->select('Id', 'account')->get();
        $users = json_decode(json_encode($users), true);
        $user_arr = array();
        foreach ($users as $u) {
            $user_arr[$u['Id']] = $u['account'];
        }

        $plans = DB::table('amazon_plan_status')->select('id', 'status_name')->get();
        $plans = json_decode(json_encode($plans), true);
        $plan_arr = array();
        foreach ($plans as $p) {
            $plan_arr[$p['id']] = $p['status_name'];
        }

        $requestMdl = db::table('amazon_buhuo_request')
            ->where('fid', '<>', 0)
            ->get(['id', 'fid']);
        $childIdList = [];
        foreach ($requestMdl as $re){
            $childIdList[$re->fid][] = $re->id;
        }
        foreach ($data as $key => $val) {
            $val->child_ids = [];
            $childIds = $childIdList[$val->id] ?? [];
            if (!empty($childIds)){
                $val->child_ids = $childIds;
            }

            if(array_key_exists($val->shop_id, $shop_arr)){
                $val->shop_name = $shop_arr[$val->shop_id];
            }else{
                $val->shop_name = '';
            }
            if(array_key_exists($val->request_userid, $user_arr)){
                $val->account = $user_arr[$val->request_userid];
            }else{
                $val->account = '';
            }
            if(array_key_exists($val->request_status, $plans)){
                $val->status_name = $plan_arr[$val->request_status];
            }else{
                $val->status_name = '';
            }
            $val->is_publish_fba = $val->is_publish_fba ? '已发布' : '未发布';
            $val->transportation_type = self::TRANSPORTATION_TYPE[$val->transportation_type] ?? '';
            $request_id = $val->id;
            $detail = Db::table('amazon_buhuo_detail')->where('request_id', $request_id)->select('request_num','box_data_detail')->get()->toArray();
//            $val->sku_count = count($detail);
            $box_num =array();
            if (!empty($detail)) {
                $box_detail = array_column($detail,'box_data_detail');
                $reqeust_num =  array_sum(array_column($detail,'request_num'));
                $val->sku_count = $reqeust_num;
                foreach ($box_detail as $detailVal){
                    if($detailVal!=''&&$detailVal!=null){
                        $box_data = json_decode($detailVal,true);
                        if(!empty($box_data)){
                            $box_num[] = array_sum($box_data);
                        }else{
                            $box_num[] = 0;
                        }
                    }else{
                        $box_num[] = 0;
                    }
                }
                $data[$key]->num = array_sum($box_num);
                $data[$key]->price = $val->logistics_price * $data[$key]->calculate_heavy;

                $quantity_received = db::table('amazon_create_goods_receive')->where('request_id',$request_id)->where('serial_no',$val->serial_no)->sum('quantity_received');
                $val->quantity_received = 0;
                if($quantity_received){
                    $val->quantity_received = $quantity_received;
                }
            }
            $val->supplier_name = '';
            $val->supplier_no = '';
            if($val->supplier_id>0){
                $supplier = db::table('suppliers')->where('Id',$val->supplier_id)->first();
                $val->supplier_name = $supplier->name;
                $val->supplier_no = !empty($supplier->supplier_no) ? $supplier->supplier_no : '请维护供应商代号';
            }


        }


        return [
            'data' => $data,
            'totalNum' => $totalNum
        ];
    }

    public function makeCodeImg($param){
        $fnsku = $param['fnsku'];
        if(empty($fnsku)){
            return[
                'code' =>'error',
                'msg' =>'缺少fnsku参数'
            ];
        }

        // $sql = "SELECT 
        //     a.client_sku,
        //     b.title
        // FROM
        // saihe_product_detail a 
        // LEFT JOIN product_detail b ON a.order_source_sku = b.sellersku
        // WHERE
        //     b.fnsku = '$fnsku'";
        // $data = DB::select($sql);



        $skus =DB::table('product_detail as a')->leftjoin('self_sku as sk',function ($join) {
            $join->on('a.sellersku', '=', 'sk.sku')->orOn('a.sellersku', '=', 'sk.old_sku');
        })->leftjoin('self_custom_sku as sc','sc.id','=','sk.custom_sku_id')->where('a.fnsku',$fnsku)->select('sc.custom_sku','sc.old_custom_sku','a.title')->first();

        $res['custom_sku'] = '';
        $res['title'] = '';

        // if($skus){
        //     $res['custom_sku'] = $skus->old_custom_sku??$skus->custom_sku;
        //     // $res['title'] = $skus->name;
        // }


        $res['img'] = "http://www.zity.cn/admin/tool/barcodegen/html/image.php?filetype=JPEG&dpi=300&scale=2&rotation=0&font_family=Arial.ttf&font_size=35&thickness=30&checksum=&code=BCGcode128&text=" .$fnsku;
        if (!empty($skus)) {
            if($skus->old_custom_sku){
                $res['custom_sku'] =$skus->old_custom_sku;
            }else{
                $res['custom_sku'] =$skus->custom_sku;
            }
            
            $res['title'] = $skus->title;
        }
        return[
            'code'=>'success',
            'data' =>$res
        ];

    }

    public function IsToken($param){
        if(!isset($param['token'])){
            return[
                'code' =>'error',
                'msg' =>'缺少token参数'
            ];
        }
        $token = $param['token'];
        $is_login = DB::table('users')->where('token',$token)->first();
        if(!$is_login){
            return false;
        }
        return true;
    }
    public function makeSkuCodeImg($param){
        $sku = $param['sku'];
        if(empty($sku)){
            return[
                'code' =>'error',
                'msg' =>'缺少sku参数'
            ];
        }


        $custom_sku = DB::table("self_custom_sku")->where('custom_sku',$sku)->orwhere('old_custom_sku',$sku)->first();

        if(!$custom_sku){
            return[
                'code' =>'error',
                'msg' =>'无此库存'
            ];
        }

        $name = $custom_sku->name;
       
        $cus = $custom_sku->old_custom_sku??$custom_sku->custom_sku;
       

        $res['img'] = "http://www.zity.cn/admin/tool/barcodegen/html/image.php?filetype=JPEG&dpi=300&scale=2&rotation=0&font_family=Arial.ttf&font_size=35&thickness=30&checksum=&code=BCGcode128&text=" .$cus;
        
        $res['custom_sku'] =  $cus;
        $res['title'] = $name;

        return[
            'code'=>'success',
            'data' =>$res
        ];

    }



   
    //获取亚马逊补货计划数据明细
//    public function buhuoPlan_data($params)
//    {
//        $plan_id = $params['plan_id'];
//        $buhuo_detail = DB::table('amazon_buhuo_detail as a')
//            ->leftJoin('amazon_buhuo_request as b','a.request_id','=','b.id')
//            ->select('a.*','b.shop_id as shopId','b.delivery_date', 'b.box_data','b.request_status','b.request_link','b.logistics_order_no','b.logistics_price','b.request_userid', 'b.transportation_date', 'b.calculate_heavy')
//            ->where('request_id',$plan_id)
//            ->get()
//            ->toArray();
//        if(!empty($buhuo_detail)){
////获取计划状态
//            $plan_status = $this->GetPlan($buhuo_detail[0]->request_status);
//            // var_dump($plan_status);
//            if($plan_status){
//                $status_name = $plan_status['status_name'];
//            }else{
//                $status_name = '';
//            }
////获取店铺名
//            $shop = $this->GetShop($buhuo_detail[0]->shopId);
//            if($plan_status){
//                $shop_name = $shop['shop_name'];
//            }else{
//                $shop_name = '';
//            }
//
//            // 店铺id
//            if($plan_status){
//                $shopId = $shop['Id'];
//            }else{
//                $shopId = '';
//            }
//
////获取运营名称
//            $user = $this->GetUsers($buhuo_detail[0]->request_userid);
//            if($plan_status){
//                $account = $user['account'];
//            }else{
//                $account = '';
//            }
//            $sku = array_column($buhuo_detail,'sku');
//            $custom_sku = array_column($buhuo_detail,'custom_sku');
//        }
//
//
//        // var_dump( $this->getBuhuoByCus('CFMTX00017-7-Yellow-3XL'));
//
//
//
//// var_dump($zuhe_cus);
//
//        // $ga = [];
//        // if(count($zuhe_cus)>1){
//        //     foreach ($zuhe_cus as $v) {
//        //         foreach ($v as $vv) {
//        //             # code...
//        //             $ga[] = $vv;
//        //         }
//        //     }
//        // }
//
//        // $custom_sku+= $ga;
//
//        // var_dump($ga);
//        // var_dump($zuhe_cus);
//        // var_dump($custom_sku);
//
////亚马逊产品数据
//        $product_detail = DB::table('product_detail')
//            ->select('sellersku','fnsku','in_stock_num','in_bound_num','transfer_num')
//            ->whereIn('sellersku',$sku)
//            ->get()
//            ->toArray();
//        $amazon = [];
//        foreach ($product_detail as $detail){
//            $amazon[$detail->sellersku] = ['fnsku'=>$detail->fnsku,'total_inventory'=>$detail->in_stock_num+$detail->in_bound_num+$detail->transfer_num];
//        }
////赛盒产品数据
//        $saihe_product = DB::table('saihe_product')
//            ->select('product_name_cn','small_image_url','client_sku')
//            ->whereIn('client_sku',$custom_sku)
//            ->get()
//            ->toArray();
//        $saihe= [];
//        foreach ($saihe_product as $product){
//            $saihe[$product->client_sku] = ['product_name_cn'=>$product->product_name_cn,'small_image_url'=>$product->small_image_url];
//        }
////赛盒库存数据
//        $saihe_inventory = DB::table('saihe_inventory')
//            ->select('good_num','warehouse_id','client_sku')
//            ->whereIn('client_sku',$custom_sku)
//            ->whereIn('warehouse_id',[2,386,560])
//            ->get()
//            ->toArray();
//        $saiheinven2 = [];
//        $saiheinven386 = [];
//        $saiheinven560 = [];
//        foreach ($saihe_inventory as $inven){
////同安fba仓库存
//            if($inven->warehouse_id==2){
//                $saiheinven2[$inven->client_sku] = $inven->good_num;
//            }
////同安自发货仓库存
//            if($inven->warehouse_id==386){
//                $saiheinven386[$inven->client_sku] = $inven->good_num;
//            }
////泉州仓库存
//            if($inven->warehouse_id==560){
//                $saiheinven560[$inven->client_sku] = $inven->good_num;
//            }
//
//        }
////自生成库存sku数据
//        $self_custom_sku = DB::table('self_custom_sku')
//            ->select('custom_sku','old_custom_sku','img','name','cloud_num','type','factory_num')
//            ->whereIn('old_custom_sku',$custom_sku)
//            ->orWhereIn('custom_sku',$custom_sku)
//            ->get()
//            ->toArray();
//        $self = [];
//        foreach ($self_custom_sku as $self_custom){
//            if($self_custom->type==2){
//                $goods_num = Db::table('self_group_custom_sku')->where('custom_sku',$self_custom->custom_sku)->count();
//            }else{
//                $goods_num = 1;
//            }
//            if($self_custom->old_custom_sku){
//                $self[$self_custom->old_custom_sku] = ['goods_num'=>$goods_num,'product_name_cn'=>$self_custom->name,'small_image_url'=>$self_custom->img,'cloud_num'=>$self_custom->cloud_num,'new_custom_sku'=>$self_custom->custom_sku,'factory_num'=>$self_custom->factory_num];
//            }
//            if($self_custom->custom_sku){
//                $self[$self_custom->custom_sku] = ['goods_num'=>$goods_num,'product_name_cn'=>$self_custom->name,'small_image_url'=>$self_custom->img,'cloud_num'=>$self_custom->cloud_num,'new_custom_sku'=>$self_custom->custom_sku,'factory_num'=>$self_custom->factory_num];
//            }
//        }
//
////补货计划中的发货量
//        $plan_num = DB::table('amazon_buhuo_detail as a')
//            ->leftJoin('amazon_buhuo_request as b','a.request_id','=','b.id')
//            ->select('a.sku','b.warehouse','a.custom_sku', 'a.request_num')
//            ->whereIn('request_status',[3,4,5,6,7])
//            ->get()
//            ->toArray();
//        $planarr1 = [];
//        $planarr2 = [];
//        $planarr3 = [];
//        foreach ($plan_num as $plan){
//            if($plan->warehouse==1){
//                if(isset($planarr1[$plan->custom_sku])){
//                    $planarr1[$plan->custom_sku] += $plan->request_num;
//                }else{
//                    $planarr1[$plan->custom_sku] = $plan->request_num;
//                }
//            }
//            if($plan->warehouse==2){
//                if(isset($planarr2[$plan->custom_sku])){
//                    $planarr2[$plan->custom_sku] += $plan->request_num;
//                }else{
//                    $planarr2[$plan->custom_sku] = $plan->request_num;
//                }
//            }
//            if($plan->warehouse==3){
//                if(isset($planarr3[$plan->custom_sku])){
//                    $planarr3[$plan->custom_sku] += $plan->request_num;
//                }else{
//                    $planarr3[$plan->custom_sku] = $plan->request_num;
//                }
//            }
//        }
//
////查询上一个月的所有订单
//        $year = date('Y');
//        $month = date('m');
//        $last_month = date('m',strtotime("last month"));
//        $day = date('d');
//        $lastday = $this->get_lastday($year, $last_month);
////上周区间
//        $startTime = date('Y-m-d 00:00:00', strtotime('-8 days',strtotime($year.'-'.$month.'-'.$day)));
//        $endTime = date('Y-m-d 00:00:00', strtotime('-1 days',strtotime($year.'-'.$month.'-'.$day)));
////上上周区间
//        $startTimeTwo = date('Y-m-d 00:00:00', strtotime('-15 days',strtotime($year.'-'.$month.'-'.$day)));
////月区间
//        $startTimeMonth = date('Y-m-d 00:00:00', strtotime("-{$lastday} days",strtotime($year.'-'.$month.'-'.$day)));
//
//        $order_data = DB::table('amazon_order_item')
//            ->select('seller_sku','quantity_ordered','amazon_time')
//            ->whereBetween('amazon_time', [$startTimeMonth, $endTime])
//            ->where('order_status','!=','Canceled')
//            ->whereIn('seller_sku',$sku)
//            ->get()
//            ->toArray();
//        $month = [];
//        $before_week = [];
//        $this_week = [];
//        foreach ($order_data as $order){
//            if(isset($month[$order->seller_sku])){
//                $month[$order->seller_sku] += $order->quantity_ordered;
//            }else{
//                $month[$order->seller_sku] = $order->quantity_ordered;
//            }
//            if($order->amazon_time>$startTimeTwo){
//                if(isset($before_week[$order->seller_sku])){
//                    $before_week[$order->seller_sku] += $order->quantity_ordered;
//                }else{
//                    $before_week[$order->seller_sku] = $order->quantity_ordered;
//                }
//            }
//            if($order->amazon_time>$startTime){
//                if(isset($this_week[$order->seller_sku])){
//                    $this_week[$order->seller_sku] += $order->quantity_ordered;
//                }else{
//                    $this_week[$order->seller_sku] = $order->quantity_ordered;
//                }
//            }
//        }
////任务备注，任务id
//        $request_id = substr(substr(json_encode(array("request_id" => "{$plan_id}")), 1), 0, -1);
//        $task_data = Db::table('tasks as a')
//            ->leftjoin('tasks_examine as b', 'a.Id', '=', 'b.task_id')
//            ->where('a.ext', 'like', "%{$request_id}%")
//            ->select('a.desc','a.Id','b.user_id','a.class_id','a.ext')
//            ->first();
//        if (!empty($task_data)) {
//            $desc = $task_data->desc;
//            $task_id = $task_data->Id;
//            $task_class = $task_data->class_id;
//            $task_ext = json_decode($task_data->ext,true);
//            $yj_saletime = $task_ext['start_time'].'~'. $task_ext['end_time'];
//        }else{
//            $desc = '';
//            $task_id = 0;
//            $task_class = 0;
//            $yj_saletime = '';
//        }
//
//        if (!empty($buhuo_detail)) {
//            foreach ($buhuo_detail as $key => $val) {
////是否组合
//
//                $cuss = $this->GetCustomSkus($val->custom_sku);
//                $buhuo_detail[$key]->type = $cuss['type']??1;
////匹配fnsku和亚马逊库存合计
//                if(array_key_exists($val->sku,$amazon)){
//                    $buhuo_detail[$key]->fnsku = $amazon[$val->sku]['fnsku'];
//                    $buhuo_detail[$key]->total_inventory = $amazon[$val->sku]['total_inventory'];
//                }else{
//                    $buhuo_detail[$key]->fnsku = '';
//                    $buhuo_detail[$key]->total_inventory = 0;
//                }
////新库存sku
//                if(array_key_exists($val->custom_sku,$self)){
//                    $buhuo_detail[$key]->new_custom_sku = $self[$val->custom_sku]['new_custom_sku'];
//                    $buhuo_detail[$key]->goods_num = $self[$val->custom_sku]['goods_num'];
//                }
//
////匹配中文名和图片
//                if(array_key_exists($val->custom_sku,$saihe)){
////赛盒数据匹配不到就匹配自己的库存sku表数据
//                    $buhuo_detail[$key]->img = $saihe[$val->custom_sku]['small_image_url'];
//                    $buhuo_detail[$key]->product_name = $saihe[$val->custom_sku]['product_name_cn'];
//                    if($buhuo_detail[$key]->img==null||$buhuo_detail[$key]->img==''){
//                        if(array_key_exists($val->custom_sku,$self)){
//                            $buhuo_detail[$key]->img = $self[$val->custom_sku]['small_image_url'];
//                        }
//                    }
//                    if($buhuo_detail[$key]->product_name==null||$buhuo_detail[$key]->product_name==''){
//                        if(array_key_exists($val->custom_sku,$self)){
//                            $buhuo_detail[$key]->product_name = $self[$val->custom_sku]['product_name_cn'];
//                        }
//                    }
//                }elseif(array_key_exists($val->custom_sku,$self)){
////匹配库存sku表数据
//                    $buhuo_detail[$key]->img = $self[$val->custom_sku]['small_image_url'];
//                    $buhuo_detail[$key]->product_name = $self[$val->custom_sku]['product_name_cn'];
//                }else{
//                    $buhuo_detail[$key]->img = '';
//                    $buhuo_detail[$key]->product_name = '';
//                }
//
//
//
//                $buhuo_detail[$key]->img = $this->GetCustomskuImg($val->custom_sku);
////获取计划增长倍数和销售状态
//                $sellersku = DB::table('self_sku')->where('sku',$val->sku)->orWhere('old_sku',$val->sku)->select('plan_multiple','goods_style')->first();
//                if(!empty($sellersku)){
//                    $buhuo_detail[$key]->plan_multiple = $sellersku->plan_multiple;
//                    $buhuo_detail[$key]->goods_style = $sellersku->goods_style;
//                }else{
//                    $buhuo_detail[$key]->plan_multiple = 1;
//                    $buhuo_detail[$key]->goods_style = 0;
//                }
////获取装箱数据
//                if ($val->box_data_detail != '') {
//                    $in_box_num = json_decode($val->box_data_detail, true);
//                    if(!empty($in_box_num)){
//                        $val->box_data_detail = array_sum($in_box_num);
//                    }else {
//                        $val->box_data_detail = 0;
//                    }
//                } else {
//                    $val->box_data_detail = 0;
//                }
//                $buhuo_detail[$key]->num_sum = null;
//                $arr = (array)($val);
//                if (isset($in_box_num) && $in_box_num != '') {
//                    $num_count = 1;
//                    $num_arr = $in_box_num;
//
//                    if (is_array($num_arr)) {
//                        $num_count = count($num_arr);
//                    }
//
//                    for ($j = 0; $j < $num_count; $j++) {
//                        $str = "number" . ($j + 1);
//                        $arr[$str] =  (int)$num_arr[$j];
//                    }
//                    $buhuo_detail[$key] = (object)($arr);
//                    $buhuo_detail[$key]->boxNum_sum = (int)array_sum($num_arr);
//                }
////同安仓fba库存
//                if(array_key_exists($val->custom_sku,$saiheinven2)){
//                    $buhuo_detail[$key]->tongAn_inventory = $saiheinven2[$val->custom_sku];
//                }else{
//                    $buhuo_detail[$key]->tongAn_inventory = 0;
//                }
////同安仓自发货库存
//                if(array_key_exists($val->custom_sku,$saiheinven386)){
//                    $buhuo_detail[$key]->self_delivery_inventory = $saiheinven386[$val->custom_sku];
//                }else{
//                    $buhuo_detail[$key]->self_delivery_inventory = 0;
//                }
////泉州仓库存
//                if(array_key_exists($val->custom_sku,$saiheinven560)){
//                    $buhuo_detail[$key]->quanzhou_inventory = $saiheinven560[$val->custom_sku];
//                }else{
//                    $buhuo_detail[$key]->quanzhou_inventory = 0;
//                }
////云仓库存
//                if(array_key_exists($val->custom_sku,$self)){
//                    $buhuo_detail[$key]->cloud_inventory = $self[$val->custom_sku]['cloud_num'];
//                }else{
//                    $buhuo_detail[$key]->cloud_inventory = 0;
//                }
////预减后同安仓库存
//                if(array_key_exists($val->custom_sku,$planarr1)){
//                    $buhuo_detail[$key]->tongAn_deduct_inventory = $buhuo_detail[$key]->tongAn_inventory - $planarr1[$val->custom_sku];
//                }else{
//                    $buhuo_detail[$key]->tongAn_deduct_inventory = $buhuo_detail[$key]->tongAn_inventory;
//                }
////预减后云仓库存
//                if(array_key_exists($val->custom_sku,$planarr3)){
//                    $buhuo_detail[$key]->cloud_deduct_inventory = $buhuo_detail[$key]->cloud_inventory - $planarr3[$val->custom_sku];
//                }else{
//                    $buhuo_detail[$key]->cloud_deduct_inventory = $buhuo_detail[$key]->cloud_inventory;
//                }
////预减后泉州仓库存
//                if(array_key_exists($val->custom_sku,$planarr2)){
//                    $buhuo_detail[$key]->quanzhou_deduct_inventory = $buhuo_detail[$key]->quanzhou_inventory - $planarr2[$val->custom_sku];
//                }else{
//                    $buhuo_detail[$key]->quanzhou_deduct_inventory = $buhuo_detail[$key]->quanzhou_inventory;
//                }
//                //工厂库存
//                if(array_key_exists($val->custom_sku,$self)){
//                    $buhuo_detail[$key]->factory_inventory = $self[$val->custom_sku]['factory_num'];
//                }else{
//                    $buhuo_detail[$key]->factory_inventory = 0;
//                }
////上周销量
//                if(array_key_exists($val->sku,$this_week)){
//                    $this_week_sale = $this_week[$val->sku];
//                }else{
//                    $this_week_sale = 0;
//                }
////上两周销量
//                if(array_key_exists($val->sku,$before_week)){
//                    $buhuo_detail[$key]->total_sales = $before_week[$val->sku];
//                }else{
//                    $buhuo_detail[$key]->total_sales = 0;
//                }
////上个月销量
//                if(array_key_exists($val->sku,$month)){
//                    $month_sale = $month[$val->sku];
//                }else{
//                    $month_sale = 0;
//                }
////近一周日销
//                $this_week_daysales = $this->daySales($this_week_sale);
////近两周日销
//                $buhuo_detail[$key]->week_daysales = $this->daySalesTwo($buhuo_detail[$key]->total_sales);
////近一月日销
//                $this_month_daysales = $this->monthSales($month_sale,$lastday);
////库存可周转天数
//                $buhuo_detail[$key]->inventory_turnover = 0;
//                if($val->goods_style==1){
//                    $buhuo_detail[$key]->inventory_turnover = $this->inventoryTurnoverStatus($buhuo_detail[$key]->total_inventory,$this_week_daysales,$val->plan_multiple);
//                }else if($val->goods_style==3){
//                    $buhuo_detail[$key]->inventory_turnover = $this->inventoryTurnoverStatus($buhuo_detail[$key]->total_inventory,$this_month_daysales,$val->plan_multiple);
//                }else{
//                    $buhuo_detail[$key]->inventory_turnover = $this->inventoryTurnoverStatus($buhuo_detail[$key]->total_inventory,$buhuo_detail[$key]->week_daysales,$val->plan_multiple);
//                }
//
//                $buhuo_detail[$key]->advice = $buhuo_detail[$key]->week_daysales*60*$val->plan_multiple - $buhuo_detail[$key]->total_inventory > 0? round($buhuo_detail[$key]->week_daysales*60*$val->plan_multiple - $buhuo_detail[$key]->total_inventory):0;
//            }
//        }
////        $totalNum = db::select("SELECT FOUND_ROWS() as total")[0]->total;
//        $box_data = DB::table('amazon_box_data')->where('request_id', '=', $plan_id)->select('heavy', 'long', 'wide', 'high', 'box_num')->get();
//        $count = count($box_data);
//        $box = array();
//        $heavy_arr = array();
//        $heavy_sum = null;
//        if (!empty($box_data)) {
//            foreach ($box_data as $k => $v) {
//                $heavy_arr[$k] = $v->heavy;
//                $str = "number" . ($k + 1);
//                $box[0][$str] = $v->heavy;
//                $box[1][$str] = $v->long;
//                $box[2][$str] = $v->wide;
//                $box[3][$str] = $v->high;
//                $box[0]['name'] = '重量';
//                $box[1]['name'] = '长度';
//                $box[2]['name'] = '宽度';
//                $box[3]['name'] = '高度';
//                $box[0]['unit'] = 'KG';
//                $box[1]['unit'] = 'CM';
//                $box[2]['unit'] = 'CM';
//                $box[3]['unit'] = 'CM';
//            }
//            $heavy_sum = array_sum($heavy_arr);
//
//        }
//        foreach ($box as $boxKey => $boxVal) {
//            $box[$boxKey] = (object)($boxVal);
//            $box[0]->heavy_sum = round($heavy_sum, 2);
//        }
//        $delivery_date = null;
//        $transport = null;
//        $request_id = null;
//        $request_link = null;
//        $box_data = null;
//        $logistics_order_no = null;
//        $logistics_price = 0;
//        $calculateHeavy = 0;
//        $freight = 0;
//        $sum = 0;
//        $transportation_date = '';
//        $transportation_type = '';
////        var_dump($data);die;
//        if (!empty($buhuo_detail)) {
//            $box_data = json_decode($buhuo_detail[0]->box_data, true);
//            $request_status = $buhuo_detail[0]->request_status;
//            $request_id = $buhuo_detail[0]->request_id;
//            $request_link = $buhuo_detail[0]->request_link;
//            $logistics_order_no = $buhuo_detail[0]->logistics_order_no;
//            $logistics_price = $buhuo_detail[0]->logistics_price;
//            $calculateHeavy = $buhuo_detail[0]->calculate_heavy;
//            $freight = round($buhuo_detail[0]->logistics_price ?? 0 * $buhuo_detail[0]->calculate_heavy ?? 0, 2);
//            $delivery_date = $buhuo_detail[0]->delivery_date;
//            $transportation_date = $buhuo_detail[0]->transportation_date;
//            $transportation_type = self::TRANSPORTATION_TYPE[$buhuo_detail[0]->transportation_type] ?? '';
//            $transport =  $buhuo_detail[0]->transportation_mode_name;
////计算补货后库存可周转天数
//            foreach ($buhuo_detail as $val2) {
//
//                $val2->num_sum = $val2->request_num;
//
//                $cusss = db::table('self_custom_sku')->where('id',$val2->custom_sku_id)->first();
//                if(!empty($cusss->old_custom_sku)){
//                    $val2->custom_sku = $cusss->old_custom_sku;
//                }
////                $val2->num_sum = $val2->courier_num + $val2->shipping_num + $val2->air_num;
//
//                $num_sum[] = $val2->num_sum;
//                if ($val2->inventory_turnover == 999) {
//                    $val2->plan_inventory_turnover = $val2->inventory_turnover;
//                } elseif($val2->inventory_turnover == -1) {
//                    $val2->plan_inventory_turnover = $val2->num_sum;
//                } else {
//                    $val2->plan_inventory_turnover = $val2->week_daysales*$val2->plan_multiple == 0 ? 0 : round(($val2->total_inventory + $val2->num_sum) / $val2->week_daysales / $val2->plan_multiple);
//                }
//
//
//
//            }
//
//
//
//            // foreach ($buhuo_detail as $k =>$val2) {
//            //     # code...
//            //     // $newdata = [];
//            //     // $newdata[0] = json_decode(json_encode($val2),true);
//            //     // $i = 1;
//            //     foreach ($zuhe_cus as $key => $value) {
//            //         # code...
//            //         if($val2->custom_sku==$key){
//            //             // $value =
//            //             // $newdata[$i] = $value;
//            //             // $i++;
//            //             $buhuo_detail[$k] =  $value;
//            //         }
//            //     }
//            //     // $buhuo_detail[$key] =  $newdata;
//
//            // }
//
//
//
////计划发货总量
//            $sum = array_sum($num_sum);
//        }
//
//
//        $zuhe_cus = [];
//        foreach ($custom_sku as $cus) {
//            # code...
//            $cuss = $this->GetCustomSkus($cus);
//            $type = $cuss['type'];
//            if($type==2){
//                $group = $this->GetGroupCustomSku($cuss['custom_sku']);
//                $group = array_column($group,'group_custom_sku');
////                var_dump($cus);
//                foreach ($group as&$v) {
//
//                    # code...
//                    $v = $this->getBuhuoByCus($v);
//                }
//                $zuhe_cus[$cus] =  $group;
//            }
//        }
//
//        // $a = $zuhe_cus;
//        // var_dump( $zuhe_cus );
//
//        // 创货件数据
//        $createGoods = DB::table('amazon_create_goods')
//            ->where('request_id', $plan_id)
//            ->get();
//
//        return [
//            'account' => $account,//运营名称
//            'shop_name' => $shop_name,//店铺名
//            'transport' => $transport,//运输方式
//            'transportation_date' => $transportation_date,
//            'transprotation_type' => $transportation_type,
//            'delivery_date' => $delivery_date,//发货日期
//            'data' => $buhuo_detail,//补货单装箱单数据
//            'zuhe_data'=>$zuhe_cus,
//            'sum' => $sum,//合计发货
//            'request_id' => $request_id,//计划id
//            'box_num' => $count,//装箱合计
//            'request_link' => $request_link,//计划链接
//            'request_status' => $request_status,//计划状态id
//            'box_data' => $box,//装箱数据
////            'totalNum' => $totalNum,//数据总量
//            'logistics_order_no' => $logistics_order_no,//物流单号
//            'logistics_price' => $logistics_price,//物流单价
//            'status_name' => $status_name,//计划状态名称
//            'desc' => $desc,//备注
//            'task_id' => $task_id,//任务id
//            'task_class' => $task_class,//任务id
//            'yj_saletime' => $yj_saletime,
//            'shop_id' => $shopId, // 店铺id
//            'create_goods' => $createGoods,
//            'calculate_heavy' => $calculateHeavy,
//            'freight' => $freight
//        ];
//    }

    //获取亚马逊补货计划数据明细
    public function buhuoPlan_data($params)
    {
        $plan_id = $params['plan_id'];
        $buhuo_detail = DB::table('amazon_buhuo_detail as a')
            ->leftJoin('amazon_buhuo_request as b','a.request_id','=','b.id')
            ->select('a.*','b.shop_id as shopId','b.delivery_date', 'b.box_data','b.request_status','b.request_link',
                'b.logistics_order_no','b.logistics_price','b.request_userid', 'b.transportation_date', 'b.calculate_heavy','b.warehouse','b.request_type','b.runboat_time','b.arrival_time','a.supplier_id','b.tag')
            ->where('request_id',$plan_id)
            ->get()
            ->toArray();
        if(!empty($buhuo_detail)){
//获取计划状态
            $plan_status = $this->GetPlan($buhuo_detail[0]->request_status);
            // var_dump($plan_status);
            if($plan_status){
                $status_name = $plan_status['status_name'];
            }else{
                $status_name = '';
            }
//获取店铺名
            $shop = $this->GetShop($buhuo_detail[0]->shopId);
            $tag = $buhuo_detail[0]->tag;
            if($plan_status){
                $shop_name = $shop['shop_name'];
            }else{
                $shop_name = '';
            }

            // 店铺id
            if($plan_status){
                $shopId = $shop['Id'];
            }else{
                $shopId = '';
            }

//获取运营名称
            $user = $this->GetUsers($buhuo_detail[0]->request_userid);
            if($plan_status){
                $account = $user['account'];
            }else{
                $account = '';
            }
            $sku = array_column($buhuo_detail,'sku_id');
            $custom_sku = array_column($buhuo_detail,'custom_sku');
            $custom_sku_id = array_column($buhuo_detail,'custom_sku_id');
        }


//亚马逊产品数据
        $product_detail = DB::table('product_detail')
            ->select('sellersku','sku_id','fnsku','in_stock_num','in_bound_num','transfer_num')
            ->whereIn('sku_id',$sku)
            ->get()
            ->toArray();
        $amazon = [];
        foreach ($product_detail as $detail){
            $amazon[$detail->sku_id] = [
                'fnsku'=>$detail->fnsku,
                'total_inventory'=>$detail->in_stock_num+$detail->in_bound_num+$detail->transfer_num,
                'in_stock_num' => $detail->in_stock_num,
                'in_bound_num' => $detail->in_bound_num,
                'transfer_num' => $detail->transfer_num,
            ];
        }

        //新仓储修改start
        $self_custom_sku = DB::table('self_custom_sku')
            ->select('id','custom_sku','old_custom_sku','img','name','cloud_num','type','factory_num','tongan_inventory','quanzhou_inventory','deposit_inventory')
            ->whereIn('id',$custom_sku_id)
            ->get()
            ->toArray();

        //获取平台的库位库存
        $cloudhouse_num = DB::table('cloudhouse_location_num as a')
            ->leftJoin('cloudhouse_warehouse_location as b', 'a.location_id', '=', 'b.id')
            ->where('a.platform_id',5)
            ->whereIn('a.custom_sku_id',$custom_sku_id )
            ->select('a.num','b.warehouse_id','a.custom_sku_id')
            ->get();

        $t_l_iven = [];
        $q_l_iven = [];
        $c_l_iven = [];
        $f_l_iven = [];
        $z_l_iven = [];

        $self = [];
        if ($cloudhouse_num){
            foreach ($cloudhouse_num as $v) {
                if($v->warehouse_id==1){
                    //同安仓
                    if(isset($t_l_iven[$v->custom_sku_id])){
                        $t_l_iven[$v->custom_sku_id]+=$v->num;
                    }else{
                        $t_l_iven[$v->custom_sku_id]=$v->num;
                    }
                }elseif($v->warehouse_id==2){
                    //泉州仓
                    if(isset($q_l_iven[$v->custom_sku_id])){
                        $q_l_iven[$v->custom_sku_id]+=$v->num;
                    }else{
                        $q_l_iven[$v->custom_sku_id]=$v->num;
                    }
                }elseif($v->warehouse_id==3){
                    //云仓
                    if(isset($c_l_iven[$v->custom_sku_id])){
                        $c_l_iven[$v->custom_sku_id]+=$v->num;
                    }else{
                        $c_l_iven[$v->custom_sku_id]=$v->num;
                    }
                }elseif($v->warehouse_id==6){
                    //工厂寄存仓
                    if(isset($f_l_iven[$v->custom_sku_id])){
                        $f_l_iven[$v->custom_sku_id]+=$v->num;
                    }else{
                        $f_l_iven[$v->custom_sku_id]=$v->num;
                    }
                }elseif($v->warehouse_id==21){
                    //工厂直发仓
                    if(isset($z_l_iven[$v->custom_sku_id])){
                        $z_l_iven[$v->custom_sku_id]+=$v->num;
                    }else{
                        $z_l_iven[$v->custom_sku_id]=$v->num;
                    }
                }
            }
        }
        //新仓储修改end
//            ->select('id', 'custom_sku','old_custom_sku','img','name','cloud_num','type','factory_num')
//            ->whereIn('old_custom_sku',$custom_sku)
//            ->orWhereIn('custom_sku',$custom_sku)
//            ->get();

        foreach ($self_custom_sku as $self_custom){
            if($self_custom->type==2){
//                $goods_num = Db::table('self_group_custom_sku')->where('custom_sku',$self_custom->custom_sku)->count();
                $goods_num = Db::table('self_group_custom_sku')->where('custom_sku_id',$self_custom->id)->count();
            }else{
                $goods_num = 1;
            }
            //新仓储修改start

            if($self_custom->id){
                $self[$self_custom->id]['goods_num'] = $goods_num;
                $self[$self_custom->id]['product_name_cn'] = $self_custom->name;
                $self[$self_custom->id]['new_custom_sku'] = $self_custom->custom_sku;
                $self[$self_custom->id]['factory_num'] = $self_custom->factory_num;

                if(isset($t_l_iven[$self_custom->id])){
                    $self[$self_custom->id]['tongan_inventory']=$t_l_iven[$self_custom->id];
                }else{
                    $self[$self_custom->id]['tongan_inventory']=0;
                }
                if(isset($c_l_iven[$self_custom->id])){
                    $self[$self_custom->id]['cloud_num']=$c_l_iven[$self_custom->id];
                }else{
                    $self[$self_custom->id]['cloud_num'] = 0;
                }
                if(isset($q_l_iven[$self_custom->id])){
                    $self[$self_custom->id]['quanzhou_inventory']=$q_l_iven[$self_custom->id];
                }else{
                    $self[$self_custom->id]['quanzhou_inventory'] = 0;
                }
                if(isset($f_l_iven[$self_custom->id])){
                    $self[$self_custom->id]['deposit_inventory']=$f_l_iven[$self_custom->id];
                }else{
                    $self[$self_custom->id]['deposit_inventory'] = 0;
                }
            }
            //新仓储修改end
        }
        //获取锁定库存

        $plan_num = $this->lock_inventory($custom_sku_id,[5]);

//查询上一个月的所有订单
        $year = date('Y');
        $month = date('m');
        $last_month = date('m',strtotime("last month"));
        $day = date('d');
        $lastday = $this->get_lastday($year, $last_month);
//上周区间
        $startTime = date('Y-m-d 00:00:00', strtotime('-8 days',strtotime($year.'-'.$month.'-'.$day)));
        $endTime = date('Y-m-d 00:00:00', strtotime('-1 days',strtotime($year.'-'.$month.'-'.$day)));
//上上周区间
        $startTimeTwo = date('Y-m-d 00:00:00', strtotime('-15 days',strtotime($year.'-'.$month.'-'.$day)));
//月区间
        $startTimeMonth = date('Y-m-d 00:00:00', strtotime("-{$lastday} days",strtotime($year.'-'.$month.'-'.$day)));

        $order_data = DB::table('amazon_order_item')
            ->select('seller_sku','quantity_ordered','amazon_time','sku_id')
            ->whereBetween('amazon_time', [$startTimeMonth, $endTime])
            ->where('order_status','!=','Canceled')
            ->whereIn('sku_id',$sku)
            ->get();

        if ($order_data){
            $order_data = $order_data->toArray();
        }
        $month = [];
        $before_week = [];
        $this_week = [];
        if ($order_data){
            foreach ($order_data as $order){
                if(isset($month[$order->sku_id])){
                    $month[$order->sku_id] += $order->quantity_ordered;
                }else{
                    $month[$order->sku_id] = $order->quantity_ordered;
                }
                if($order->amazon_time>$startTimeTwo){
                    if(isset($before_week[$order->sku_id])){
                        $before_week[$order->sku_id] += $order->quantity_ordered;
                    }else{
                        $before_week[$order->sku_id] = $order->quantity_ordered;
                    }
                }
                if($order->amazon_time>$startTime){
                    if(isset($this_week[$order->sku_id])){
                        $this_week[$order->sku_id] += $order->quantity_ordered;
                    }else{
                        $this_week[$order->sku_id] = $order->quantity_ordered;
                    }
                }
            }
        }

//任务备注，任务id
        $request_id = substr(substr(json_encode(array("request_id" => "{$plan_id}")), 1), 0, -1);
        $task_data = Db::table('tasks as a')
            ->leftjoin('tasks_examine as b', 'a.Id', '=', 'b.task_id')
            ->where('a.ext', 'like', "%{$request_id}%")
            ->select('a.desc','a.Id','b.user_id','a.class_id','a.ext')
            ->first();
        if (!empty($task_data)) {
            $desc = $task_data->desc;
            $task_id = $task_data->Id;
            $task_class = $task_data->class_id;
            $task_ext = json_decode($task_data->ext,true);
            $yj_saletime = $task_ext['start_time'].'~'. $task_ext['end_time'];
        }else{
            $desc = '';
            $task_id = 0;
            $task_class = 0;
            $yj_saletime = '';
        }

        if (!empty($buhuo_detail)) {
            foreach ($buhuo_detail as $key => $val) {
//是否组合
                $cuss = $this->GetCustomSkus($val->custom_sku);
                $buhuo_detail[$key]->type = $cuss['type'] ?? 1;

                $val->user_name = $this->GetUsers($val->user_id)['account'] ?? '';
//匹配fnsku和亚马逊库存合计
                if (array_key_exists($val->sku_id, $amazon)) {
                    $buhuo_detail[$key]->fnsku = $amazon[$val->sku_id]['fnsku'];
                    $buhuo_detail[$key]->total_inventory = $amazon[$val->sku_id]['total_inventory'];
                    $buhuo_detail[$key]->in_stock_num = $amazon[$val->sku_id]['in_stock_num'];
                    $buhuo_detail[$key]->in_bound_num = $amazon[$val->sku_id]['in_bound_num'];
                    $buhuo_detail[$key]->transfer_num = $amazon[$val->sku_id]['transfer_num'];
                }else{
                    $buhuo_detail[$key]->fnsku = '';
                    $buhuo_detail[$key]->total_inventory = 0;
                    $buhuo_detail[$key]->in_stock_num = 0;
                    $buhuo_detail[$key]->in_bound_num = 0;
                    $buhuo_detail[$key]->transfer_num = 0;
                }

//匹配中文名，图片，库存
                $buhuo_detail[$key]->img = $this->GetCustomskuImg($val->custom_sku);
                if (isset($self[$val->custom_sku_id])) {
                    $buhuo_detail[$key]->product_name = $self[$val->custom_sku_id]['product_name_cn'];
                    $buhuo_detail[$key]->new_custom_sku = $self[$val->custom_sku_id]['new_custom_sku'];
                    $buhuo_detail[$key]->goods_num = $self[$val->custom_sku_id]['goods_num'];
                    $buhuo_detail[$key]->tongAn_inventory = $self[$val->custom_sku_id]['tongan_inventory'];
                    $buhuo_detail[$key]->quanzhou_inventory = $self[$val->custom_sku_id]['quanzhou_inventory'];
                    $buhuo_detail[$key]->cloud_inventory = $self[$val->custom_sku_id]['cloud_num'];
                    $buhuo_detail[$key]->factory_inventory = $self[$val->custom_sku_id]['factory_num'];
                } else {
                    $buhuo_detail[$key]->product_name = '';
                    $buhuo_detail[$key]->new_custom_sku = '';
                    $buhuo_detail[$key]->goods_num = 0;
                    $buhuo_detail[$key]->tongAn_inventory = 0;
                    $buhuo_detail[$key]->quanzhou_inventory = 0;
                    $buhuo_detail[$key]->cloud_inventory = 0;
                    $buhuo_detail[$key]->factory_inventory = 0;
                }

//获取计划增长倍数和销售状态
                $sellersku = DB::table('self_sku')->where('sku', $val->sku)->orWhere('old_sku', $val->sku)->select('plan_multiple', 'goods_style')->first();
                if (!empty($sellersku)) {
                    $buhuo_detail[$key]->plan_multiple = $sellersku->plan_multiple;
                    $buhuo_detail[$key]->goods_style = $sellersku->goods_style;
                } else {
                    $buhuo_detail[$key]->plan_multiple = 1;
                    $buhuo_detail[$key]->goods_style = 0;
                }
//获取装箱数据
                if ($val->box_data_detail != '') {
                    $in_box_num = json_decode($val->box_data_detail, true);
                    if (!empty($in_box_num)) {
                        $val->box_data_detail = array_sum($in_box_num);
                    } else {
                        $val->box_data_detail = 0;
                    }
                } else {
                    $val->box_data_detail = 0;
                }
                $buhuo_detail[$key]->num_sum = null;
                $arr = (array)($val);
                if (isset($in_box_num) && $in_box_num != '') {
                    $num_count = 1;
                    $num_arr = $in_box_num;

                    if (is_array($num_arr)) {
                        $num_count = count($num_arr);
                    }

                    for ($j = 0; $j < $num_count; $j++) {
                        $str = "number" . ($j + 1);
                        $arr[$str] = (int)$num_arr[$j];
                    }
                    $buhuo_detail[$key] = (object)($arr);
                    $buhuo_detail[$key]->boxNum_sum = (int)array_sum($num_arr);
                }


                //新仓储修改start
                if ($plan_num) {
                    if (isset($plan_num[$val->custom_sku_id][1])) {
                        $buhuo_detail[$key]->tongAn_deduct_inventory = $buhuo_detail[$key]->tongAn_inventory - $plan_num[$val->custom_sku_id][1];
                    } else {
                        $buhuo_detail[$key]->tongAn_deduct_inventory = $buhuo_detail[$key]->tongAn_inventory;
                    }
                    if (isset($plan_num[$val->custom_sku_id][2])) {
                        $buhuo_detail[$key]->quanzhou_deduct_inventory = $buhuo_detail[$key]->quanzhou_inventory - $plan_num[$val->custom_sku_id][2];
                    } else {
                        $buhuo_detail[$key]->quanzhou_deduct_inventory = $buhuo_detail[$key]->quanzhou_inventory;
                    }
                    if (isset($plan_num[$val->custom_sku_id][3])) {
                        $buhuo_detail[$key]->cloud_deduct_inventory = $buhuo_detail[$key]->cloud_inventory - $plan_num[$val->custom_sku_id][3];
                    } else {
                        $buhuo_detail[$key]->cloud_deduct_inventory = $buhuo_detail[$key]->cloud_inventory;
                    }
                }
                //新仓储修改end


//上周销量
                if (array_key_exists($val->sku_id, $this_week)) {
                    $this_week_sale = $this_week[$val->sku_id];
                } else {
                    $this_week_sale = 0;
                }
//上两周销量
                if (array_key_exists($val->sku_id, $before_week)) {
                    $buhuo_detail[$key]->total_sales = $before_week[$val->sku_id];
                } else {
                    $buhuo_detail[$key]->total_sales = 0;
                }
//上个月销量
                if (array_key_exists($val->sku_id, $month)) {
                    $month_sale = $month[$val->sku_id];
                } else {
                    $month_sale = 0;
                }
//近一周日销
                $this_week_daysales = $this->daySales($this_week_sale);
//近两周日销
                $buhuo_detail[$key]->week_daysales = $this->daySalesTwo($buhuo_detail[$key]->total_sales);
//近一月日销
                $this_month_daysales = $this->monthSales($month_sale, $lastday);
//库存可周转天数
                $buhuo_detail[$key]->inventory_turnover = 0;
                if ($val->goods_style == 1) {
                    $buhuo_detail[$key]->inventory_turnover = $this->inventoryTurnoverStatus($buhuo_detail[$key]->total_inventory, $this_week_daysales, $val->plan_multiple);
                } else if ($val->goods_style == 3) {
                    $buhuo_detail[$key]->inventory_turnover = $this->inventoryTurnoverStatus($buhuo_detail[$key]->total_inventory, $this_month_daysales, $val->plan_multiple);
                } else {
                    $buhuo_detail[$key]->inventory_turnover = $this->inventoryTurnoverStatus($buhuo_detail[$key]->total_inventory, $buhuo_detail[$key]->week_daysales, $val->plan_multiple);
                }

                $buhuo_detail[$key]->advice = $buhuo_detail[$key]->week_daysales * 60 * $val->plan_multiple - $buhuo_detail[$key]->total_inventory > 0 ? round($buhuo_detail[$key]->week_daysales * 60 * $val->plan_multiple - $buhuo_detail[$key]->total_inventory) : 0;

            }
        }
//        $totalNum = db::select("SELECT FOUND_ROWS() as total")[0]->total;
        $box_data = DB::table('amazon_box_data')->where('request_id', '=', $plan_id)->select('heavy', 'long', 'wide', 'high', 'box_num')->get();
        $count = count($box_data);
        $box = array();
        $heavy_arr = array();
        $heavy_sum = null;
        if (!empty($box_data)) {
            foreach ($box_data as $k => $v) {
                $heavy_arr[$k] = $v->heavy;
                $str = "number" . ($k + 1);
                $box[0][$str] = $v->heavy;
                $box[1][$str] = $v->long;
                $box[2][$str] = $v->wide;
                $box[3][$str] = $v->high;
                $box[0]['name'] = '重量';
                $box[1]['name'] = '长度';
                $box[2]['name'] = '宽度';
                $box[3]['name'] = '高度';
                $box[0]['unit'] = 'KG';
                $box[1]['unit'] = 'CM';
                $box[2]['unit'] = 'CM';
                $box[3]['unit'] = 'CM';
            }
            $heavy_sum = array_sum($heavy_arr);

        }
        foreach ($box as $boxKey => $boxVal) {
            $box[$boxKey] = (object)($boxVal);
            $box[0]->heavy_sum = round($heavy_sum, 2);
        }
        $delivery_date = null;
        $transport = null;
        $request_id = null;
        $request_link = null;
        $box_data = null;
        $logistics_order_no = null;
        $logistics_price = 0;
        $calculateHeavy = 0;
        $freight = 0;
        $sum = 0;
        $transportation_date = '';
        $transportation_type = '';
//        var_dump($data);die;
        $request_type =  1;
        $runboat_time = '';
        $arrival_time = '';
        if (!empty($buhuo_detail)) {
            $box_data = json_decode($buhuo_detail[0]->box_data, true);
            $request_type =  $buhuo_detail[0]->request_type;
            $runboat_time = $buhuo_detail[0]->runboat_time;
            $arrival_time = $buhuo_detail[0]->arrival_time;
            $request_status = $buhuo_detail[0]->request_status;
            $request_id = $buhuo_detail[0]->request_id;
            $request_link = $buhuo_detail[0]->request_link;
            $logistics_order_no = $buhuo_detail[0]->logistics_order_no;
            $logistics_price = $buhuo_detail[0]->logistics_price;
            $calculateHeavy = $buhuo_detail[0]->calculate_heavy;
            $freight = round($buhuo_detail[0]->logistics_price ?? 0 * $buhuo_detail[0]->calculate_heavy ?? 0, 2);
            $delivery_date = $buhuo_detail[0]->delivery_date;
            $transportation_date = $buhuo_detail[0]->transportation_date;
            $transportation_type = self::TRANSPORTATION_TYPE[$buhuo_detail[0]->transportation_type] ?? '';
            $transport =  $buhuo_detail[0]->transportation_mode_name;
//计算补货后库存可周转天数
            foreach ($buhuo_detail as $val2) {
                $getOldSku = $this->GetOldSku($val2->sku);
                if($getOldSku){
                    $val2->sku = $getOldSku;
                }
                $val2->num_sum = $val2->request_num;

                $cusss = db::table('self_custom_sku')->where('id',$val2->custom_sku_id)->first();
                if(!empty($cusss->old_custom_sku)){
                    $val2->custom_sku = $cusss->old_custom_sku;
                }
//                $val2->num_sum = $val2->courier_num + $val2->shipping_num + $val2->air_num;

                $num_sum[] = $val2->num_sum;
                if ($val2->inventory_turnover == 999) {
                    $val2->plan_inventory_turnover = $val2->inventory_turnover;
                } elseif($val2->inventory_turnover == -1) {
                    $val2->plan_inventory_turnover = $val2->num_sum;
                } else {
                    $val2->plan_inventory_turnover = $val2->week_daysales*$val2->plan_multiple == 0 ? 0 : round(($val2->total_inventory + $val2->num_sum) / $val2->week_daysales / $val2->plan_multiple);
                }
                $cus_box = db::table('self_custom_sku_box')->where('custom_sku_id',$val2->custom_sku_id)->where('suppliers_id',$val2->supplier_id)->first();
                $val2->weight = 0;
                $val2->box_weight = 0;
                if($cus_box){
                    $val2->weight = (double)$cus_box->product_weight;
                    $val2->box_weight = (double)$cus_box->box_weight;
                }
                
            }



//计划发货总量
            $sum = array_sum($num_sum);
        }


        $custom_sku = array_column($buhuo_detail, 'custom_sku');

//        $zuhe_cus = [];
//        foreach ($custom_sku as $cus) {
//            # code...
//            $cuss = $this->GetCustomSkus($cus);
//            $type = $cuss['type'];
//            if($type==2){
//                $group = $this->GetGroupCustomSku($cuss['custom_sku']);
//
//                $group = array_column($group,'group_custom_sku');
//                // var_dump($group);
////                var_dump($cus);
//                foreach ($group as&$v) {
//
//                    # code...
//                    $v = $this->getBuhuoByCusB($v);
//                }
//                $zuhe_cus[$cus] =  $group;
//            }
//        }
        // $a = $zuhe_cus;
        // var_dump( $zuhe_cus );

        // 创货件数据
        $createGoods = DB::table('amazon_create_goods')
            ->where('request_id', $plan_id)
            ->get();

        $goods_box = DB::table('goods_transfers_box')->where('order_no',$plan_id)->select('box_code')->first();

        $tag_name = '';
        if($tag>0){
            $tag_name = db::table('amazon_tag')->where('id',$tag)->first()->name??'';
        }

        return [
            'account' => $account,//运营名称
            'shop_name' => $shop_name,//店铺名
            'transport' => $transport,//运输方式
            'transportation_date' => $transportation_date,
            'transprotation_type' => $transportation_type,
            'delivery_date' => $delivery_date,//发货日期
            'data' => $buhuo_detail,//补货单装箱单数据
//            'zuhe_data'=>$zuhe_cus,
            'sum' => $sum,//合计发货
            'request_id' => $request_id,//计划id
            'runboat_time'=>$runboat_time,
            'arrival_time'=>$arrival_time,
            'box_num' => $count,//装箱合计
            'request_link' => $request_link,//计划链接
            'request_status' => $request_status,//计划状态id
            'request_type' => $request_type,//计划状态id
            'box_data' => $box,//装箱数据
//            'totalNum' => $totalNum,//数据总量
            'logistics_order_no' => $logistics_order_no,//物流单号
            'logistics_price' => $logistics_price,//物流单价
            'status_name' => $status_name,//计划状态名称
            'desc' => $desc,//备注
            'task_id' => $task_id,//任务id
            'task_class' => $task_class,//任务id
            'yj_saletime' => $yj_saletime,
            'shop_id' => $shopId, // 店铺id
            'create_goods' => $createGoods,
            'calculate_heavy' => $calculateHeavy,
            'freight' => $freight,
            'box_code' => $goods_box->box_code ?? '',
            'tag'=>$tag,
            'tag_name'=>$tag_name
        ];
    }



    //数据单数据
    public function GetDataOrderListM($params){
        if(isset($params['plan_id'])){
            $id = $params['plan_id'];
        }

        if(isset($params['box_code'])){
           $box =  db::table('goods_transfers_box')->where('box_code',$params['box_code'])->first();
           if(!$box){
                return ['type'=>'fail','msg'=>'无此箱号对应任务'];
           }

           $id = $box->order_no;
        }

        $res = db::table('goods_transfers as a')->leftjoin('goods_transfers_detail as b','a.order_no','=','b.order_no')->where('a.order_no',$id)->select('b.*','a.shop_id')->get();

        $zuhe = [];
        foreach ($res as $v) {
            # code...
            $v->sku = '';
            $v->fnsku = '';
            $sku = db::table('self_sku')->where('custom_sku_id',$v->custom_sku_id)->where('shop_id',$v->shop_id)->first();
            if($sku){
                if(!empty($sku->old_sku)){
                    $v->sku = $sku->old_sku;
                }else{
                    $v->sku = $sku->sku;
                }
                $product = db::table('product_detail')->where('sku_id',$sku->id)->first();
                if($product){
                    $v->fnsku = $product->fnsku;
                }
            }

            $v->shop_name = $this->GetShop($v->shop_id)['shop_name'];
            $cus = $this->GetCustomSkus($v->custom_sku);
            $v->type = $cus['type'];
            if($v->type==2){
                $zuhe[$v->custom_sku_id] = $this->GetGroupCustomSku($v->custom_sku);
            }
        }

        return ['type'=>'success','data'=>$res,'zuhe'=>$zuhe];

    }


    public function GetPdfNew($params){

        if(isset($params['plan_id'])){
           $box =  db::table('goods_transfers_box')->where('box_code',$params['plan_id'])->first();
           if(!$box){
                   $id = $params['plan_id'];
           }else{
               $id = $box->order_no;
           }
        }

        $user = DB::table('users')->where('token',$params['token'])->select('Id')->first();
        if(empty($user)){
            return ['type'=>'fail','msg'=>'用户错误'];
        }

        $task_data = Db::table('tasks')
            ->where('ext', 'like', "%{$id}%")
            ->whereNotIn('class_id', [127])
            ->where('is_deleted', 0)
            ->select('Id','desc')
            ->first();
        if(empty($task_data)){
            return ['type'=>'fail','msg'=>'未查询到该任务'];
        }else{
            $task_node =  Db::table('tasks_node')->where('task_id', $task_data->Id)->select('Id')->first();
            $task_son =  Db::table('tasks_son')->where('task_id', $task_data->Id)->select('Id','user_id')->first();
        }
        $param['token'] = $params['token'];
        $param['task_id'] = $task_data->Id;
        $param['tasks_node_id'] = $task_node->Id;
        $param['Id'] = $task_son->Id;

        if($user->Id==$task_son->user_id){
            $task = new Task();
            $task_res = $task->task_accept_model($param);
        }

        $res = db::table('goods_transfers_box as b')->leftjoin('goods_transfers_box_detail as a','a.box_id','=','b.id')->where('b.order_no',$id)->where('a.box_num','>',0)->select('a.*','b.box_code')->get()->toarray();


        $sort = array_column($res,'location_ids');
        // $sort =  sort($sort);
        array_multisort($sort,SORT_ASC,$res);


        $plan_res = db::table('goods_transfers')->where('order_no',$id)->first();

        if(empty($plan_res)){
            return ['type'=>'fail','msg'=>'未查询到对应的出库任务:'.$id];
        }

        if($plan_res->type_detail==6){
            $amazon_buhuo_request = db::table('amazon_buhuo_request')->where('id',$id)->first();
            if($amazon_buhuo_request->request_status==4&&$user->Id==$task_son->user_id){
                db::table('amazon_buhuo_request')->where('id',$id)->update(['request_status'=>5]);
            }
            $plan_res->transportation_mode_name = $amazon_buhuo_request->transportation_mode_name??'';
            $plan_res->text = $task_data->desc;
        }


        $plan_res->account = $this->GetUsers($plan_res->user_id)['account'];
        $plan_res->shop_name = $this->GetShop($plan_res->shop_id)['shop_name'];

        $zuheres = db::table('goods_transfers_detail')->where('order_no',$id)->get();
        $zuhe = [];
        $zuhenum = [];
        foreach ($zuheres as $v) {
            # code...
            $zuheskus = $this->GetCustomSkus($v->custom_sku);
            // if($zuheskus['type']==2){
            //     $zuhenum[$v->custom_sku] = $v->request_num;
            //     $zuhe[$v->custom_sku] = $this->GetGroupCustomSku($v->custom_sku);
            // }
        }

        $zuhee = [];
        foreach ($zuhe as $zk => $zv) {
            # code...
            $zvvv = [];
            foreach ($zv as $zvv) {
                # code...
                $zvvv[]=$zvv['group_custom_sku'];
            }

            $zuhee[$zk.'*'.$zuhenum[$zk]] = implode(',',$zvvv);
        }

        foreach ($res as&$v) {
            # code...
            $location_code = db::table('cloudhouse_warehouse_location')->where('id',$v->location_ids)->first();
            $v->location_code = '';
            if($location_code){
                $v->location_code = $location_code->location_code;
            }

            $cuscout = db::table('custom_sku_count')->where('location_code',$v->location_code)->where('custom_sku_id',$v->custom_sku_id)->get()->toarray();
            $no = array_column($cuscout,'no');
            $v->no = implode(',',$no);
            $skus = db::table('self_sku')->where('shop_id',$plan_res->shop_id)->where('custom_sku_id',$v->custom_sku_id)->first();
            $v->fnsku = '';
            $v->name_cn = '';
            $cus = db::table('self_custom_sku')->where('id',$v->custom_sku_id)->first();
            if($cus){
                $v->name_cn = $cus->name;
            }
            if($skus){
                $pro = db::table('product_detail')->where('sku_id',$skus->id)->first();
                if($pro){
                    $v->fnsku = $pro->fnsku;
                }
            }
            $box_code = $v->box_code??'';
            $v->img = $this->GetCustomskuImg($v->custom_sku);
        }

        $plan_res->box_code = $box_code??'';
        $plan_res->id = $plan_res->order_no;

        return ['msg'=>'请求成功','type'=>'success','data'=>$res,'plan_res'=>$plan_res,'zuhe'=>$zuhee];
    }



    public function GetErrInventory($params){
        $list = DB::table('goods_transfers as a')->leftJoin('goods_transfers_detail as b','a.order_no','=','b.order_no')->whereIn('a.type_detail',[6,7,8,9,10])->where('a.is_push',2)->select(DB::raw('sum(b.transfers_num) as num'),'b.custom_sku_id')->groupby('b.custom_sku_id')->get();
        $list_lock = db::table('cloudhouse_location_num')->select(DB::raw('sum(lock_num) as lock_num'),'custom_sku_id')->groupby('custom_sku_id')->get();

        $lock_arr = [];
        foreach ($list_lock as $v) {
            # code...
            $lock_arr[$v->custom_sku_id] = $v->lock_num;
        }

        $return_arr = [];
        foreach ($list as $v) {
            # code...
            if(isset($lock_arr[$v->custom_sku_id])){

                if($lock_arr[$v->custom_sku_id]!=$v->num){
                    $d['custom_sku_id'] = $v->custom_sku_id;
                    $d['transfer_num'] = $v->num;
                    $d['lock_num'] = $lock_arr[$v->custom_sku_id];
                    $return_arr[] = $d;
                }
            }
        }

        $posttype = $params['posttype']??1;
        if($posttype==2){
            $p['title']='错误数据'.time();
            $p['title_list']  = [
                'custom_sku_id'=>'库存skuid',
                'transfer_num'=>'transfer_num',
                'lock_num'=>'lock_num',
            ];

            // $this->excel_expord($p);

            $p['data'] =   $return_arr;
            $p['user_id'] = 312;
            $p['type'] = '错误数据-导出';
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }
        return ['type'=>'success','data'=>$return_arr];
    }
    //获取pdf导出的减货数量
    public function GetPdfJonCusRes($params){
        $id = $params['plan_id'];
        $custom_sku =  $params['custom_sku'];
        $custom_res= db::table('self_custom_sku')->where('custom_sku',$custom_sku)->orwhere('old_custom_sku',$custom_sku)->first();
        if(!$custom_res){
            return ['type'=>'success','data'=>[]];
        }
        $custom_sku_id = $custom_res->id;

        $boxs = db::table('goods_transfers_box')->where('order_no',$id)->first();
        if(!$boxs){
            return ['type'=>'success','data'=>[]];
        }
        $box_id = $boxs->id;
        $box_detail = db::table('goods_transfers_box_detail')->where('box_id',$box_id)->where('custom_sku_id',$custom_sku_id)->get();
        if(!$box_detail){
            return ['type'=>'success','data'=>[]];
        }
        $return = [];
        foreach ($box_detail as $v) {
            # code...
            $location_code = 0;
            $locations = db::table('cloudhouse_warehouse_location')->where('id',$v->location_ids)->first();
            if($locations){
                $location_code = $locations->location_code;
            }
            $num = $location_code.":".$v->box_num."\n";

            $return_one['location_code']= $location_code;
            $return_one['num']  = $v->box_num;
            $return[] = $return_one;
        }        
        return ['type'=>'success','data'=>$return];
    }
    //根据获取的sku查找可能需要补货的sku
//    public function may_buhuo($params)
//    {
//        $data = $params['data'];
//        if (!empty($data)) {
//            $shop_name = $data[0]['shop_name'];
//            $account = $data[0]['account'];
//            foreach ($data as $val) {
//                $sku[] = "'" . $val['sku'] . "'";
//                $custom_sku[] = "'" . $val['custom_sku'] . "'";
//            }
//            $sku = implode(",", $sku);
//            $custom_sku = implode(",", $custom_sku);
//        }
//        $year = date('Y');
//        $daySum = isset($params['daySum']) ? $params['daySum'] : 14;
//        $lastDay = isset($params['lastDay']) ? $params['lastDay'] : 30;
//        $month = isset($params['month']) ? $params['month'] : date('m');
//        $day = isset($params['day']) ? $params['day'] : date('d');
//        $thisDaySum = 7;
//        $thisMonthSum = $lastDay;
//        if ($day > 0 && $day < 8) {
//            $this_date = date('Y-m-d', strtotime($year . '-' . ($month - 1) . '-22'));
//            $before_date = date('Y-m-d', strtotime($year . '-' . ($month - 1) . '-15'));
//            $before2_date = date('Y-m-d', strtotime($year . '-' . ($month - 1) . '-08'));
//            $before3_date = date('Y-m-d', strtotime($year . '-' . ($month - 1) . '-01'));
//            $thisDaySum = $lastDay - 21;
//        } elseif ($day > 7 && $day < 15) {
//            $this_date = date('Y-m-d', strtotime($year . '-' . $month . '-01'));
//            $before_date = date('Y-m-d', strtotime($year . '-' . ($month - 1) . '-22'));
//            $before2_date = date('Y-m-d', strtotime($year . '-' . ($month - 1) . '-15'));
//            $before3_date = date('Y-m-d', strtotime($year . '-' . ($month - 1) . '-08'));
//        } elseif ($day > 14 && $day < 22) {
//            $this_date = date('Y-m-d', strtotime($year . '-' . $month . '-08'));
//            $before_date = date('Y-m-d', strtotime($year . '-' . $month . '-01'));
//            $before2_date = date('Y-m-d', strtotime($year . '-' . ($month - 1) . '-22'));
//            $before3_date = date('Y-m-d', strtotime($year . '-' . ($month - 1) . '-15'));
//        } else {
//            $this_date = date('Y-m-d', strtotime($year . '-' . $month . '-15'));
//            $before_date = date('Y-m-d', strtotime($year . '-' . $month . '-08'));
//            $before2_date = date('Y-m-d', strtotime($year . '-' . $month . '-01'));
//            $before3_date = date('Y-m-d', strtotime($year . '-' . ($month - 1) . '-22'));
//        }
//        $where = "a.custom_sku in ($custom_sku) and a.sku not in ($sku) and s.shop_name='$shop_name' and u.account='$account' and date='$this_date'";
//        $skuSql = "SELECT
//            t.id,
//            t.plan_multiple,
//            a.sku,
//            a.fnsku,
//            a.img,
//            a.father_asin,
//            a.asin,
//            a.category_id,
//            a.sales_status,
//            a.gender,
//            a.custom_sku,
//            u.account,
//            s.shop_name,
//            s.fba_warehouse_id,
//            t.quantity_ordered,
//            t.date
//        FROM
//            amazon_traffic t
//        LEFT JOIN amazon_skulist a ON t.sku = a.sku
//        LEFT JOIN shop s ON a.shop_id = s.Id
//        LEFT JOIN users u ON a.user_id = u.Id
//        WHERE
//            $where
//        group by
//            a.custom_sku";
//        $skuData = DB::select($skuSql);
//        //查询品类表所有品类数据拼接到$categoryName
//        $categorySql = "select `id`,`product_typename` from amazon_category where 1=1";
//        $categoryData = DB::select($categorySql);
//        $categoryName = array();
//        if ($categoryData) {
//            foreach ($categoryData as $categoryVal) {
//                $categoryName[$categoryVal->id] = $categoryVal->product_typename;
//            }
//        };
//        //查询销售状态表所有状态数据拼接到$statusName
//        $statusSql = "select `id`,`category_status` from amazon_category_status where 1=1";
//        $statusData = DB::select($statusSql);
//        $statusName = array();
//        if ($statusData) {
//            foreach ($statusData as $statusVal) {
//                $statusName[$statusVal->id] = $statusVal->category_status;
//            }
//        }
//        //循环计算数据
//        $data1 = array();
//        $data2 = array();
//        $data3 = array();
//        if (!empty($skuData)) {
//            foreach ($skuData as $val) {
//                $sku = $val->sku;
//                $asin = $val->asin;
//                $category_id = $val->category_id;
//                $sales_status = $val->sales_status;
//                //查找品类
//                if (array_key_exists($category_id, $categoryName)) {
//                    $val->category_name = $categoryName[$category_id];
//                } else {
//                    $val->category_name = '';
//                }
//                //查找销售款式
//                if (array_key_exists($sales_status, $statusName)) {
//                    $val->category_status = $statusName[$sales_status];
//                } else {
//                    $val->category_status = '';
//                }
//                $beforeSql = "select `quantity_ordered`,`date` from amazon_traffic where `sku`='{$sku}' and `date` like '$year%'";
//                $beforeData = DB::select($beforeSql);
//                $year_sales = array();
//                $val->before_quantity_ordered = 0;//上上周销量
//                $before2_quantity_ordered = 0;//上上上周销量
//                $before3_quantity_ordered = 0;//上上上上周销量
//                foreach ($beforeData as $before) {
//                    $year_sales[] = $before->quantity_ordered;
//                    if ($before->date == $before_date) {
//                        $val->before_quantity_ordered = $before->quantity_ordered;
//                    }
//                    if ($before->date == $before2_date) {
//                        $before2_quantity_ordered = $before->quantity_ordered;
//                    }
//                    if ($before->date == $before3_date) {
//                        $before3_quantity_ordered = $before->quantity_ordered;
//                    }
//                }
//                $val->year_total = array_sum($year_sales);//本年总计销量
//                //获得当日凌晨的时间戳
//                $today = strtotime(date("Y-m-d"), time());
//                //根据sku找赛盒库存
//                $fba_warehouse_id = $val->fba_warehouse_id;
//                $val->tongAn_inventory = null;//同安仓库存
//                $val->in_warehouse_inventory = null;//fba在仓库存
//                $val->reserved_inventory = null;//预留库存
//                $val->in_road_inventory = null;//在途库存
//                $val->tongAn_deduct_inventory = null;//同安仓预扣库存
//                $inventorySql = "SELECT
//                            a.asin,a.warehouse_id,a.good_num,a.api_update_time
//                        FROM
//                            saihe_inventory a
//                        LEFT JOIN saihe_product_detail b ON a.sku = b.saihe_sku
//                        WHERE  b.order_source_sku = '$sku'
//                        AND a.warehouse_id in (2,386,$fba_warehouse_id)
//                        ";
//                $inventory = DB::select($inventorySql);
//                $tonganArr = array();
//                if (!empty($inventory)) {
//                    foreach ($inventory as $inventoryVal) {
//                        if ($inventoryVal->warehouse_id == 2 || $inventoryVal->warehouse_id == 386) {
//                            $tonganArr[] = $inventoryVal->good_num;
//                        }
//                        if ($inventoryVal->warehouse_id == $fba_warehouse_id) {
//                            if ($inventoryVal->asin == $asin && $inventoryVal->api_update_time > $today) {
//                                $saihe_inwarehouse_inventory = $inventoryVal->good_num;
//                                $api_update_time = $inventoryVal->api_update_time;
//                            }
//                        }
//                    }
//                    $val->tongAn_inventory = array_sum($tonganArr);
//                }
//                //根据sku找亚马逊库存
//                $AMZinventorySql = "SELECT
//                            in_stock_num,in_bound_num,transfer_num,update_time
//                        FROM
//                            product_detail
//                        WHERE  sellersku = '$sku'
//                        ";
//                $AMZinventory = DB::select($AMZinventorySql);
//                if (empty($AMZinventory)) {
//                    //如果亚马逊接口库存没取到则取赛盒库存
//                    if (!empty($inventory) && isset($saihe_inwarehouse_inventory)) $val->in_warehouse_inventory = $saihe_inwarehouse_inventory;
//                } else {
//                    if (isset($api_update_time) && isset($saihe_inwarehouse_inventory)) {
//                        //如果亚马逊接口库存比赛盒的更新时间早则取赛盒库存
//                        if ($api_update_time > $AMZinventory[0]->update_time) {
//                            $val->in_warehouse_inventory = $saihe_inwarehouse_inventory;
//                        } else {
//                            //如果亚马逊接口库存比赛盒的更新时间晚则取亚马逊库存
//                            $val->in_warehouse_inventory = $AMZinventory[0]->in_stock_num;
//                        }
//                    } else {
//                        $val->in_warehouse_inventory = $AMZinventory[0]->in_stock_num;
//                    }
//                    $val->reserved_inventory = $AMZinventory[0]->transfer_num;
//                    $val->in_road_inventory = $AMZinventory[0]->in_bound_num;
//                }
//                //合计库存
//                $val->total_inventory = $val->in_warehouse_inventory + $val->reserved_inventory + $val->in_road_inventory;
//                $tongAn_deductSql = "SELECT
//                            b.courier_num,b.shipping_num,b.air_num
//                        FROM
//                            amazon_buhuo_detail b
//                        LEFT JOIN amazon_buhuo_request a ON a.id = b.request_id
//                        WHERE  b.sku = '$sku'
//                        AND a.request_status in (1,2);
//                        ";
//                $tongAn_deduct = DB::select($tongAn_deductSql);
//                if (!empty($tongAn_deduct)) {
//                    //如果该sku存在计划发货数量则扣除
//                    $deduct_inventory = array();
//                    foreach ($tongAn_deduct as $deduct) {
//                        $deduct_inventory[] = $deduct->courier_num + $deduct->shipping_num + $deduct->air_num;
//                    }
//                    $tongAn_deduct_inventory = array_sum($deduct_inventory);//计划发货数量总和
//                    $val->tongAn_deduct_inventory = $val->tongAn_inventory - $tongAn_deduct_inventory;
//                } else {
//                    //如果不存在计划发货数量则等于同安仓库存
//                    $val->tongAn_deduct_inventory = $val->tongAn_inventory;
//                }
//
//                //近一月合计销量
//                $month_total = $val->quantity_ordered + $val->before_quantity_ordered + $before2_quantity_ordered + $before3_quantity_ordered;
//                //近两周合计销量
//                $val->total_sales = $val->quantity_ordered + $val->before_quantity_ordered;
//                //本周日销
//                $this_weekDaysales = round($val->quantity_ordered / $thisDaySum, 2);
//                //近两周日销
//                $val->week_daysales = 0;
//                //近一月日销
//                $this_monthDaysales = round($month_total / $thisMonthSum, 2);
//                if ($val->total_sales != 0) $val->week_daysales = round(($val->total_sales) / $daySum, 2);
//                //库存可周转天数
//                if ($val->total_inventory != 0 && $val->week_daysales == 0) {
//                    $val->inventory_turnover = 999;
//                } elseif ($val->total_inventory == 0 && $val->week_daysales == 0) {
//                    $val->inventory_turnover = -1;
//                } elseif ($val->total_inventory == 0 && $val->week_daysales != 0) {
//                    $val->inventory_turnover = 0;
//                } else {
//                    $val->inventory_turnover = round($val->total_inventory / $val->week_daysales / $val->plan_multiple);
//                }
//                //补货建议
//                $val->courier = 0;//补货建议快递
//                $val->air = 0;//补货建议空运
//                $val->shipping = 0;//补货建议海运
//
//                if ($val->sales_status == 1 || $val->sales_status == 2) {
//                    if ($val->sales_status == 1) {
//                        //爆款补货建议合计:近1周日销*销售计划增长倍数（运营可调整）*60天-库存合计
//                        $replenishment_total1 = round($this_weekDaysales * $val->plan_multiple * 60 - $val->total_inventory);
//                        $val->replenishment_total = $replenishment_total1 > 0 ? $replenishment_total1 : 0;
//                        //在库可销售天数<10,快递补货数量=近1周日销*10
//                        if ($val->inventory_turnover < 10) $val->courier = round($this_weekDaysales * 10);
//                        //空运=近1周日销*销售计划增长倍数*40天-库存合计-快递
//                        $air = round($this_weekDaysales * $val->plan_multiple * 40 - $val->total_inventory - $val->courier);
//                        $val->air = $air > 0 ? $air : 0;
//                    }
//                    if ($val->sales_status == 2) {
//                        //基础款补货建议合计:近2周日销*60天*销售计划增长倍数（运营可调整）-库存合计
//                        $replenishment_total2 = round($val->week_daysales * $val->plan_multiple * 60 - $val->total_inventory);
//                        $val->replenishment_total = $replenishment_total2 > 0 ? $replenishment_total2 : 0;
//                        //在库可销售天数<10,快递补货数量=近2周日销*10
//                        if ($val->inventory_turnover < 10) $val->courier = round($val->week_daysales * 10);
//                        //空运=近2周日销*销售计划增长倍数*40天-库存合计-快递
//                        $air = round($val->week_daysales * $val->plan_multiple * 40 - $val->total_inventory - $val->courier);
//                        $val->air = $air > 0 ? $air : 0;
//                    }
//                    //需补货总量-空运数量-快递数量
//                    $shipping = $val->replenishment_total - $val->air - $val->courier;
//                    $val->shipping = $shipping > 0 ? $shipping : 0;
//                } else {
//                    //清仓款补货建议合计:只能补海运=近1个月日销*60天-库存合计
//                    $replenishment_total = round($this_monthDaysales * 60 - $val->total_inventory);
//                    $val->replenishment_total = $replenishment_total > 0 ? $replenishment_total : 0;
//                    $val->shipping = $val->replenishment_total;
//                }
//                $val->courier_num = 0;//补货快递数量
//                $val->air_num = 0;//补货建议数量
//                $val->shipping_num = 0;//补货建议数量
//                //补货提醒
//                if ($val->inventory_turnover > 90) {
//                    $val->replenishment_remind = '3';
//                } elseif ($val->inventory_turnover > 60 && $val->inventory_turnover < 90) {
//                    $val->replenishment_remind = '2';
//                    $data2[] = $val;
//                } elseif ($val->inventory_turnover >= 0 && $val->inventory_turnover < 60) {
//                    $val->replenishment_remind = '1';
//                    $data1[] = $val;
//                }
//            }
//        }
//        $data = array_merge($data1, $data2);
//        $totalNum = count($data);
//        array_multisort(array_column($data, 'id'), SORT_ASC, $data);
//
//        return [
//            'data' => $data,
//            'totalNum' => $totalNum
//        ];
//    }

    public function AutoBuhuo($params){
        $sku_id = $params['sku_id'];
        $num = $params['num'];
        $query['sku_id'][] = $sku_id;
        $query['limit'] = 10000;
        $data = $this->getBuhuoWarnNew($query);
        if(empty($data['data'])){
            return['type'=>'fail','msg'=>'无此数据'];
        }
        foreach ($data['data'] as $v) {
            $res = json_decode(json_encode($v),true);
            //同安 泉州 云仓
            $tongan =   $res['tongan_deduct_request_num'] ;
            $quanzhou =   $res['quanzhou_deduct_request_num'] ;
            $cloud =   $res['cloud_deduct_request_num'] ;
            $return['tongan_num'] = 0;
            $return['quanzhou_num'] = 0;
            $return['cloud_num'] = 0;
            if(($tongan+$quanzhou+$cloud)<$num){
                return['type'=>'fail','msg'=>'库存数量不足'];
            }
            if($num<=$tongan){
                $return['tongan_num'] = $num;
                return['type'=>'success','data'=> $return];
            }
            $return['tongan_num'] = $tongan;
            $num = $num-$tongan;

            if($num<=$quanzhou){
                $return['quanzhou_num'] = $num;
                return['type'=>'success','data'=> $return];
            }
            $return['quanzhou_num'] = $quanzhou;
            $num = $num-$quanzhou;
            $return['cloud_num'] =  $num;
            return['type'=>'success','data'=> $return];
        }

    }

    public function ReSendBuhuoRequest($params){
        $id = $params['plan_id'];
        $res = db::table('amazon_buhuo_detail')->where('request_id',$id)->get();
        $bh = db::table('amazon_buhuo_request')->where('id',$id)->first();
        $data = [];
        foreach ($res as $v) {
            # code...
            $d['sku'] = $v->sku;
            $d['request_num'] = $v->request_num;
            $data[] = $d;
            $transportation_mode_name = $bh->transportation_mode_name??"";
        }

        $tasks = db::table('tasks')->where('ext','like','%'.$id.'%')->first();
        $task = [];
        if($tasks){
            $task['user_fz'] = $tasks->user_fz;
            $ext = json_decode($tasks->ext,true);
            $task['start_time'] = $ext['start_time'];
            $task['end_time'] = $ext['end_time'];
            $taske= db::table('tasks_examine')->where('task_id',$tasks->Id)->get()->toarray();
            $task['user_sh'] = array_column($taske,'user_id');
            $task['tag'] = $bh->tag;
            $transportation_mode = db::table('transportation_mode')->where('name', $transportation_mode_name)->first();
            if($transportation_mode){
                $task['transportation_id'] = $transportation_mode->id;
            }
        }


        $return = $this->replenish_excel_list($data);

        $return['task'] = $task;
        return $return;
    }

    //补货excel导入后返回列表数据
    public function replenish_excel_list($params)
    {
        // $i = 1;
        $sku_ids =[];
        $returns = [];
        // $customSkus = [];
        foreach ($params as  $value) {
            # code...
            if (!empty($value['sku'])) {
                $skus = db::table('self_sku')->where('sku',$value['sku'])->orwhere('old_sku',$value['sku'])->first();
                if(!$skus){
                    return ['type'=>'fail','msg'=>'无此sku:'.$value['sku']];
                }

                $sku_ids[]= $skus->id;

                $returns[$skus->id]['request_num'] = $value['request_num'];
                $returns[$skus->id]['custom_sku'] =  $skus->custom_sku;
                // $customSku = $skus->custom_sku_id ?? '';
                // if (!in_array($customSku, $customSkus)){
                //     $customSkus[] = $customSku;
                // }
                
            }
        }


        $query['sku_id'] = $sku_ids;
        $query['limit'] = 10000;
        $data = $this->getBuhuoWarnNew($query);

        $new_return  = [];
        foreach ($data['data'] as $v) {
            $res = json_decode(json_encode($v),true);
            $res['request_num'] = (int)$returns[$v->sku_id] ['request_num'];
            // $res['custom_sku'] = $returns[$v->sku_id] ['custom_sku'];
            $new_return[] = $res;
        }

        

        // exit;
        // $customSkus = [];
        // foreach ($params as $key => $value) {
        //     # code...
        //     if (!empty($value['sku'])) {
        //         $skuMdl = $this->skuModel::query()
        //             ->where('sku', $value['sku'])
        //             ->orWhere('old_sku', $value['sku'])
        //             ->first();
        //         $customSku = $skuMdl->custom_sku ?? '';
        //         if (!in_array($customSku, $customSkus)){
        //             $customSkus[] = $customSku;
        //         }
        //         $sku['sku'] = $value['sku'];
        //         $sku['shipping_num'] = $value['shipping_num'];
        //         $sku['air_num'] = $value['air_num'];
        //         $sku['courier_num'] = $value['courier_num'];

        //         // $data = $this->get_buhuo_detail($sku);
        //         $data = $this->getBuhuoWarnBySku($sku);
        //         // $res = array();
        //         // $res = array_merge((array)$data, (array)$value);
        //         $return[$key] = $data['data'];
        //         // $return[$key]['res'] = $value;
        //         $i++;
        //     }
        // }
        // 组合sku数据
        // $zuhe_cus = [];
        // foreach ($customSkus as $cus) {
        //     # code...
        //     $cuss = Db::table('self_custom_sku')->where('id',$cus)->first();
        //     if($cuss){
        //         $type = $cuss->type;
        //         if($type==2){
        //             $gres = $this->GetGroupCustomSkuMinInventory($cuss->custom_sku);
        //             $v->tongan_num = $gres['tongan_num'];
        //             $v->quanzhou_num =  $gres['quanzhou_num'];
        //             $v->cloud_num =  $gres['cloud_num'];
        //             // $group = $this->GetGroupCustomSku($cuss->custom_sku);
        //             // $group = array_column($group,'group_custom_sku');
        //             // foreach ($group as $key =>$v) {
        //             //     $v = $this->getBuhuoByCus($v);

        //             //     if(empty($v)){
        //             //         unset($group[$key]);
        //             //     }else{
        //             //         $group[$key] = $v;
        //             //     }
        //             // }
        //             // $zuhe_cus[$cus] =  $group;
        //         }
        //     }
            
        // }

        return [
            'type'=>'success',
            'data' => $new_return,
            'totalNum' => count($new_return)
        ];
    }


//    public function getBuhuoWarnBySku($params)
//    {
//
//
//        $daySum = isset($params['daySum']) ? $params['daySum'] : 14;//近两周天数
//        $lastDay = isset($params['lastDay']) ? $params['lastDay'] : 30;//近一月天数
//        $month = isset($params['month']) ? $params['month'] : date('m');//月
//        $day = isset($params['day']) ? $params['day'] : date('d');//日
//        $year = date('Y');//年
//        $thisDaySum = 7;//近一周天数
//        //上周
//        $startTime = date('Y-m-d 00:00:00', strtotime('-8 days',strtotime($year.'-'.$month.'-'.$day)));
//        $endTime = date('Y-m-d 00:00:00', strtotime('-1 days',strtotime($year.'-'.$month.'-'.$day)));
//        //上上周
//        $startTimeTwo = date('Y-m-d 00:00:00', strtotime('-15 days',strtotime($year.'-'.$month.'-'.$day)));
//        $endTimeTwo = date('Y-m-d 00:00:00', strtotime('-8 days',strtotime($year.'-'.$month.'-'.$day)));
//        //月
//        $startTimeMonth = date('Y-m-d 00:00:00', strtotime("-{$lastDay} days",strtotime($year.'-'.$month.'-'.$day)));
//        $endTimeMonth = $endTime;
//        //年
//        $startTimeYear = $year.'-01-01 :00:00:00';
//        $endTimeYear = $year.'-12-31 :23:59:59';
//        $thisDaySum = 7;
//
//
//
//        $list = Db::table('self_sku as sk')->leftjoin('self_custom_sku as sc','sk.custom_sku_id', '=', 'sc.id')->leftjoin('self_spu as sp','sk.spu_id','=','sp.id')->leftjoin('self_color_size as cz','sc.size','=','cz.identifying');
//
//        if (!empty($params['sku'])) {
//            $sku = $params['sku'];
//            $list= $list->where('sk.sku',$sku)->orwhere('sk.old_sku',$sku);
//        }
//
//        $list = $list ->orderby('sc.spu','ASC')->orderby('sc.color','ASC')->orderby('cz.sort','ASC')
//            ->select('sk.*','sp.old_spu','sp.one_cate_id','sp.two_cate_id','sp.three_cate_id','sc.old_custom_sku','sc.cloud_num','sp.type as sputype','sc.id as custom_sku_id',
//                'sc.factory_num','sc.color','sc.size','sp.id as spu_id','sk.id as sku_id')->first();
//
//
//        //查询销售状态表所有状态数据拼接到$statusName
//        $statusSql = "select `id`,`category_status` from amazon_category_status";
//        $statusData = DB::select($statusSql);
//        $statusName = array();
//        if ($statusData) {
//            foreach ($statusData as $statusVal) {
//                $statusName[$statusVal->id] = $statusVal->category_status;
//            }
//        }
//
//        if (!empty($list)) {
//
//            if($list->old_sku){
//                $product = DB::table('product_detail')->where('sellersku',$list->old_sku)->orwhere('sellersku',$list->sku)->first();
//            }else{
//                $product = DB::table('product_detail')->where('sellersku',$list->sku)->first();
//            }
//
//            // $product = DB::table('product_detail')->where('sku_id',$list->id)->first();
//
//            $val = $list;
//
//
//
//            $val->shipping_num = $params['shipping_num']??0;
//            $val->air_num = $params['air_num']??0;
//            $val->courier_num = $params['courier_num']??0;
//
//                //父asin，fusku，asin
//
//            $val->fnsku = '';
//            $val->father_asin = $val->fasin;
//            if($product){
//                $val->fnsku = $product->fnsku;
//            }
//
//            $sku = $val->sku;
////                $custom_sku = $val->custom_sku;
//                // $category_id = $val->category_id;
////                if($val->old_custom_sku){
////                    $saihedetail = DB::table('saihe_product')->where('client_sku',$val->old_custom_sku)->select('small_image_url')->first();
////                }else{
////                    $saihedetail = DB::table('saihe_product')->where('client_sku',$val->custom_sku)->select('small_image_url')->first();
////                }
////                if($saihedetail){
//            $val->img =  $this->GetCustomskuImg($val->custom_sku);
////                }
////                if(!$val->img){
////                    if($val->old_custom_sku){
////                        $saihedetail = DB::table('saihe_product')->where('client_sku',$val->custom_sku)->orwhere('client_sku',$val->old_custom_sku)->select('small_image_url')->first();
////                    }else{
////                        $saihedetail = DB::table('saihe_product')->where('client_sku',$val->custom_sku)->select('small_image_url')->first();
////                    }
////                    if($saihedetail){
////                        $val->img = $saihedetail->small_image_url;
////                    }
////                }
//
//                $sales_status = $val->sales_status;
//                //查找品类
//                $val->one_cate = '';
//                $oneres = $this->GetCategory($val->one_cate_id);
//                $val->one_cate = $oneres['name'];
//                $val->two_cate = '';
//                $twores = $this->GetCategory($val->two_cate_id);
//                $val->two_cate = $twores['name'];
//                $val->three_cate = '';
//                $threeres = $this->GetCategory($val->three_cate_id);
//                $val->three_cate = $threeres['name'];
//
//                //店铺名
//                $val->shop_name = '';
//                $shopres = $this->GetShop($val->shop_id);
//                $val->shop_name = $shopres['shop_name'];
//
//                //运营人员
//                $val->operate_user = '';
//                $users = $this->GetUsers($val->operate_user_id);
//                $val->operate_user = $users['account'];
//
//                //查找销售款式
//                if (array_key_exists($sales_status, $statusName)) {
//                    $val->category_status = $statusName[$sales_status];
//                } else {
//                    $val->category_status = '';
//                }
//                //库存
//                $val->tongAn_inventory = null;//同安fba仓库存
//                $val->self_delivery_inventory = null;//同安自发货仓库存
//                $val->in_warehouse_inventory = null;//fba在仓库存
//                $val->reserved_inventory = null;//预留库存
//                $val->in_road_inventory = null;//在途库存
//                $val->tongAn_deduct_inventory = null;//同安仓预扣库存
//
//
//
//                $getSaiheInventoryByOtherres['custom_sku'][0] = $val->custom_sku;
//                $getSaiheInventoryByOtherres['custom_sku'][1] = $val->old_custom_sku;
//                // var_dump( $getInventoryByOtherres);
//                // $saihe_inventory = $this->getSaiheInventoryBycusSku($getSaiheInventoryByOtherres);
//                // $val->tongAn_inventory = $saihe_inventory['tongAn_inventory'] ?? 0;
//                // $val->quanzhou_inventory = $saihe_inventory['quanzhou_inventory'] ?? 0;
//
//                $val->tongAn_inventory = 0;
//                $val->quanzhou_inventory = 0;
//
//                $find_custom_sku = $list->custom_sku;
//                if($list->old_custom_sku){
//                    $find_custom_sku  = $list->old_custom_sku;
//                }
//
//                $saihe_inventory = Db::table('saihe_inventory')->whereIn('warehouse_id',array(2,386,560))->where('client_sku',$find_custom_sku)->get();
//                if($saihe_inventory){
//                    foreach ($saihe_inventory as $sinventory) {
//                        # code...
//                        if($sinventory->warehouse_id ==560){
//                            $val->quanzhou_inventory = $sinventory->good_num;
//                        }else{
//                            $val->tongAn_inventory+= $sinventory->good_num;
//                        }
//                    }
//                }
//
//                // $inventorys = Db::table('product_detail')->where('sku_id',$val->id)->first();
//
//                $inventory['in_warehouse_inventory'] = 0;
//                $inventory['reserved_inventory'] = 0;
//                $inventory['in_road_inventory'] = 0;
//                if($product){
//                    $inventory['in_warehouse_inventory'] = $product->in_stock_num;
//                    $inventory['reserved_inventory'] = $product->transfer_num;
//                    $inventory['in_road_inventory'] = $product->in_bound_num;
//                }
//
//
//                $val->in_warehouse_inventory =  $inventory['in_warehouse_inventory'];
//                $val->reserved_inventory =  $inventory['reserved_inventory'];
//                $val->in_road_inventory =  $inventory['in_road_inventory'];
//                // $getInventoryByOtherres['sku'][0] = $sku;
//                // $getInventoryByOtherres['sku'][1] = $val->old_sku;
//                // // var_dump( $getInventoryByOtherres);
//                // $inventory = $this->getInventoryByOther_buhuo($getInventoryByOtherres);
//                // // $val->self_delivery_inventory = $inventory['self_delivery_inventory'] ?? 0;
//                // $val->in_warehouse_inventory = $inventory['in_warehouse_inventory'] ?? 0;
//                // $val->reserved_inventory = $inventory['reserved_inventory'] ?? 0;
//                // $val->in_road_inventory = $inventory['in_road_inventory'] ?? 0;
//
//                // $getInventoryByOtherres['sku'][0] = $sku;
//                // $getInventoryByOtherres['sku'][1] = $val->old_sku;
//                // $inventory = $this->getInventoryByOther($getInventoryByOtherres);
//                // $val->tongAn_inventory = $inventory['tongAn_inventory'] ?? 0;
//                // $val->quanzhou_inventory = $inventory['quanzhou_inventory'] ?? 0;
//                // // $val->self_delivery_inventory = $inventory['self_delivery_inventory'] ?? 0;
//                // $val->in_warehouse_inventory = $inventory['in_warehouse_inventory'] ?? 0;
//                // $val->reserved_inventory = $inventory['reserved_inventory'] ?? 0;
//                // $val->in_road_inventory = $inventory['in_road_inventory'] ?? 0;
//                $val->total_inventory = $val->in_warehouse_inventory + $val->reserved_inventory + $val->in_road_inventory;
//
//                $getDeductInventoryres['sku'] = $val->custom_sku;
//                $getDeductInventoryres['old_sku'] = $val->old_custom_sku;
//                $getDeductInventoryres['warehouse'] = 1;
//                //同安补货计划数量合计
//                $tongAn_deduct_inventory = $this->getDeductInventory($getDeductInventoryres) ?? 0;
//                //泉州补货计划数量合计
//                $getDeductInventoryres['warehouse'] = 2;
//                $quanzhou_deduct_inventory = $this->getDeductInventory($getDeductInventoryres) ?? 0;
//                //云仓补货计划数量合计
//                $getDeductInventoryres['warehouse'] = 3;
//                $cloud_deduct_inventory = $this->getDeductInventory($getDeductInventoryres) ?? 0;
//
//                if ($tongAn_deduct_inventory > 0) {
//                    //如果该sku存在计划fab发货数量则扣除
//                    $val->tongAn_deduct_inventory = $val->tongAn_inventory - $tongAn_deduct_inventory;
//                } else {
//                    //如果不存在计划发货数量则等于同安仓库存
//                    $val->tongAn_deduct_inventory = $val->tongAn_inventory;
//                }
//
//                if ($quanzhou_deduct_inventory > 0) {
//                    //如果该sku存在计划fab发货数量则扣除
//                    $val->quanzhou_deduct_inventory = $val->quanzhou_inventory - $tongAn_deduct_inventory;
//                } else {
//                    //如果不存在计划发货数量则等于泉州仓库存
//                    $val->quanzhou_deduct_inventory = $val->quanzhou_inventory;
//                }
//
//                if ($cloud_deduct_inventory > 0) {
//                    //如果该sku存在计划fab发货数量则扣除
//                    $val->cloud_deduct_inventory = $val->cloud_num - $cloud_deduct_inventory;
//                } else {
//                    //如果不存在计划发货数量则等于云仓库存
//                    $val->cloud_deduct_inventory = $val->cloud_num;
//                }
//
//                 //销量
//                // //上周销量
//                $wholeParams['start_time'] = $startTime;
//                $wholeParams['end_time'] = $endTime;
//                $wholeParams['sku'] = $val->sku;
//                $wholeParams['old_sku'] = $val->old_sku;
//                $dataWhole = $this->getDatawholeByOtherNew($wholeParams);
//                $val->quantity_ordered = $dataWhole;
//                // //上两周销量
//                $wholeParams['start_time'] = $startTimeTwo;
//                $wholeParams['end_time'] = $endTimeTwo;
//                $wholeParams['sku'] = $val->sku;
//                $wholeParams['old_sku'] = $val->old_sku;
//                $dataWholeTwo = $this->getDatawholeByOtherNew($wholeParams);
//                $val->before_quantity_ordered = $dataWholeTwo;
//                $year_sales = array();
//                //$val->before_quantity_ordered = 0;//上上周销量
//                $before2_quantity_ordered = 0;//上上上周销量
//                $before3_quantity_ordered = 0;//上上上上周销量
//
//                // //本年总计销量
//                // $wholeParams['start_time'] = $startTimeYear;
//                // $wholeParams['end_time'] = $endTimeYear;
//                // $wholeParams['sku'] = $val->sku;
//                // $wholeParams['old_sku'] = $val->old_sku;
//                // $dataWholeYear = $this->getDatawholeByOtherNew($wholeParams);
//                // $val->year_total = $dataWholeYear;
//                // //根据sku找去年销量
//                // if (array_key_exists($val->sku, $lastsaleArr)) {
//                //     $val->lastyear_sales = $lastsaleArr[$val->sku];
//                // }else{
//                //     $val->lastyear_sales = 0;
//                // }
//                // $val->last_year_daySales = round($val->lastyear_sales / 365, 2);//去年日销
//
//                // //近一月合计销量
//                $wholeParams['start_time'] = $startTimeMonth;
//                $wholeParams['end_time'] = $endTimeMonth;
//                $wholeParams['sku'] = $val->sku;
//                $wholeParams['old_sku'] = $val->old_sku;
//                $dataWholeMoth = $this->getDatawholeByOtherNew($wholeParams);
//                $month_total = $dataWholeMoth;
//                //近两周合计销量
//                $val->total_sales = $val->quantity_ordered + $val->before_quantity_ordered;
//                //本周日销
//                $val->this_week_daysales = 0;
//                $this_weekDaysales = round($val->quantity_ordered / $thisDaySum, 2);
//                if ($this_weekDaysales > 0) $val->this_week_daysales = $this_weekDaysales;
//                //近两周日销
//                $val->week_daysales = 0;
//                //近一月日销
//                $this_monthDaysales = round($month_total / $lastDay, 2);
//                if ($val->total_sales != 0) $val->week_daysales = round(($val->total_sales) / $daySum, 2);
//                //库存可周转天数
//                if ($val->total_inventory != 0 && $val->week_daysales == 0) {
//                    $val->inventory_turnover = 999;
//                } elseif ($val->total_inventory == 0 && $val->week_daysales == 0) {
//                    $val->inventory_turnover = -1;
//                } elseif ($val->total_inventory == 0 && $val->week_daysales != 0) {
//                    $val->inventory_turnover = 0;
//                } else {
//                    if ($sales_status == 1) {  //爆款
//                        $val->inventory_turnover = $this->inventoryTurnoverStatus($val->total_inventory, $val->this_week_daysales, $val->plan_multiple);
//                    } elseif ($sales_status == 2) {  //利润款
//                        $val->inventory_turnover = $this->inventoryTurnoverStatus($val->total_inventory, $val->week_daysales, $val->plan_multiple);
//                    } elseif ($sales_status == 3) {   //清仓款
//                        $val->inventory_turnover = $this->inventoryTurnoverStatus($val->total_inventory, $this_monthDaysales, $val->plan_multiple);
//                    } else {
//                        $val->inventory_turnover = $this->inventoryTurnoverStatus($val->total_inventory, $val->week_daysales, $val->plan_multiple);
//                    }
//                }
//                //补货建议
//                $val->courier = 0;//补货建议快递
//                $val->air = 0;//补货建议空运
//                $val->shipping = 0;//补货建议海运
//
//                $ReplenData['sales_status'] = $val->sales_status;
//                $ReplenData['this_weekDaysales'] = $this_weekDaysales; //近1周日销
//                $ReplenData['plan_multiple'] = $val->plan_multiple; //销售计划增长倍数
//                $ReplenData['total_inventory'] = $val->total_inventory; //total_inventory
//                $ReplenData['inventory_turnover'] = $val->inventory_turnover; //在库可销售天数
//                $ReplenData['courier'] = 0; //快递
//                $ReplenData['week_daysales'] = $val->week_daysales; //近2周日销
//                $ReplenData['this_monthDaysales'] = $this_monthDaysales; //近1个月日销
//
//                $Replen = $this->getReplen($ReplenData);
////                $local_inventory = $val->tongAn_inventory + $val->quanzhou_inventory + $val->cloud_num;
//                $val->courier = $Replen['courier'] ;//补货建议快递
//
//                $val->air = $Replen['air'];//补货建议空运
//                $val->shipping = $Replen['shipping'];//补货建议海运
//                $val->replenishment_total = $Replen['replenishment_total'];//补货合计
//                // $val->shipping_num = 0;
//                // $val->air_num = 0;
//                // $val->courier_num = 0;
//                //补货提醒
//                /*if ($val->inventory_turnover >= 0 && $val->inventory_turnover < 60) {
//                    $val->buhuo_status = 1;
//                }
//                if ($val->inventory_turnover >= 60 && $val->inventory_turnover < 90) {
//                    $val->buhuo_status = 2;
//                }
//                if ($val->inventory_turnover > 90) {
//                    $val->buhuo_status = 3;
//                }*/
//                //新旧sku替换
//
//                if($val->old_sku){
//                    $val->sku = $val->old_sku;
//                }
//                if($val->old_custom_sku){
//                    $val->custom_sku = $val->old_custom_sku;
//                }
//                if($val->old_spu){
//                    $val->spu = $val->old_spu;
//                }
//
//            }
//        return [
//            'data' => $val,
//        ];
//
//    }



    //根据sku获取补货数据
    public function get_buhuo_detail($sku)
    {
        $day = date('d');
        $lastDay = 30;
        $year = date('Y');
        $month = date('m');
        $daySum = 14;
        $thisMonthSum = $lastDay;
        $thisDaySum = 7;
        //上周
        $startTime = date('Y-m-d 00:00:00', strtotime('-8 days',strtotime($year.'-'.$month.'-'.$day)));
        $endTime = date('Y-m-d 00:00:00', strtotime('-1 days',strtotime($year.'-'.$month.'-'.$day)));
        //上上周
        $startTimeTwo = date('Y-m-d 00:00:00', strtotime('-15 days',strtotime($year.'-'.$month.'-'.$day)));
        $endTimeTwo = date('Y-m-d 00:00:00', strtotime('-8 days',strtotime($year.'-'.$month.'-'.$day)));

        $startTimeMonth = date('Y-m-d 00:00:00', strtotime("-{$lastDay} days",strtotime($year.'-'.$month.'-'.$day)));
        $endTimeMonth = $endTime;


        $self_sku = DB::table('self_sku')->where('sku',$sku)->orWhere('old_sku',$sku)->select()->get()->toArray();
        if(empty($self_sku)){
            $amazon_skulist = DB::table('amazon_skulist')->where('sku',$sku)->select()->get()->toArray();
            $skuData = $amazon_skulist;
        }else{
            $skuData = $self_sku;
        }
        if (!empty($skuData)) {
            foreach ($skuData as $val) {
                //运营
                $val->account = '';
                $account = $this->GetUsers($val->user_id);
                if($account){
                    $val->account = $account['account'];
                }
                //店铺
                $val->shop_name = '';
                $shop_name = $this->GetShop($val->shop_id);
                if($shop_name){
                    $val->shop_name = $shop_name['shop_name'];
                }

                $custom_sku = $val->custom_sku;
                $img =  DB::table('self_custom_sku')->where('custom_sku',$custom_sku)->orWhere('old_custom_sku',$custom_sku)->select('img','old_custom_sku')->first();
                if($img){
                    $val->custom_sku = $img->old_custom_sku??$img->custom_sku;
                    $val->img = '';
                    if(!$img->img){
                        if($img->old_custom_sku){
                            $saihedetail = DB::table('saihe_product')->where('client_sku',$img->custom_sku)->orwhere('client_sku',$img->old_custom_sku)->select('small_image_url')->first();
                        }else{
                            $saihedetail = DB::table('saihe_product')->where('client_sku',$img->custom_sku)->select('small_image_url')->first();
                        }
                        $val->img = $saihedetail->small_image_url;
                    }else{
                        $val->img = $img->img;
                    }
     
                }
                //库存
                $val->tongAn_inventory = null;//同安仓库存
                $val->in_warehouse_inventory = null;//fba在仓库存
                $val->reserved_inventory = null;//预留库存
                $val->in_road_inventory = null;//在途库存
                $val->tongAn_deduct_inventory = null;//同安仓预扣库存

                $inventory = $this->getInventoryBySku($sku, $custom_sku);

                $val->tongAn_inventory = $inventory['tongAn_inventory'] ?? 0;
                $val->in_warehouse_inventory = $inventory['in_warehouse_inventory'] ?? 0;
                $val->reserved_inventory = $inventory['reserved_inventory'] ?? 0;
                $val->in_road_inventory = $inventory['in_road_inventory'] ?? 0;
                $val->fnsku = $inventory['fnsku'];
                $val->total_inventory = $val->in_warehouse_inventory + $val->reserved_inventory + $val->in_road_inventory;

                $tongAn_deduct_inventory = $this->getDeductInventory($custom_sku) ?? 0;
                if ($tongAn_deduct_inventory > 0) {
                    //如果该sku存在计划发货数量则扣除
                    $val->tongAn_deduct_inventory = $val->tongAn_inventory - $tongAn_deduct_inventory;
                } else {
                    //如果不存在计划发货数量则等于同安仓库存
                    $val->tongAn_deduct_inventory = $val->tongAn_inventory;
                }

                if(isset($val->old_sku)){
                    $wholeParams['old_sku'] = $val->old_sku;
                }
                $wholeParams['sku'] = $sku;
                //销量
                //上周销量
                $wholeParams['start_time'] = $startTime;
                $wholeParams['end_time'] = $endTime;
                $dataWhole = $this->getDatawholeByOtherNew($wholeParams);
                $val->quantity_ordered = $dataWhole;
                //上两周销量
                $wholeParams['start_time'] = $startTimeTwo;
                $wholeParams['end_time'] = $endTimeTwo;
                $dataWholeTwo = $this->getDatawholeByOtherNew($wholeParams);
                $val->before_quantity_ordered = $dataWholeTwo;

                //近一月合计销量
                $wholeParams['start_time'] = $startTimeMonth;
                $wholeParams['end_time'] = $endTimeMonth;
                $dataWholeMoth = $this->getDatawholeByOtherNew($wholeParams);
                $month_total = $dataWholeMoth;
                //根据sku找去年销量
                $val->lastyear_sales = 0;
                $lastYear = date('Y') - 1;
                $lastYearSql = "select `total_sales` from amazon_year_sale where `sku`='{$sku}' and `year`='{$lastYear}'";
                $lastYearData = DB::select($lastYearSql);
                if (!empty($lastYearData)) $val->lastyear_sales = $lastYearData[0]->total_sales;
                $val->last_year_daySales = round($val->lastyear_sales / 365, 2);//去年日销

                //近两周合计销量
                $val->total_sales = $val->quantity_ordered + $val->before_quantity_ordered;
                //本周日销
                $val->this_week_daysales = 0;
                $this_weekDaysales = round($val->quantity_ordered / $thisDaySum, 2);
                if ($this_weekDaysales > 0) $val->this_week_daysales = $this_weekDaysales;
                //近两周日销
                $val->week_daysales = 0;
                //近一月日销
                $this_monthDaysales = round($month_total / $lastDay, 2);
                if ($val->total_sales != 0) $val->week_daysales = round(($val->total_sales) / $daySum, 2);

                //库存可周转天数
                if ($val->total_inventory != 0 && $val->week_daysales == 0) {
                    $val->inventory_turnover = 999;
                } elseif ($val->total_inventory == 0 && $val->week_daysales == 0) {
                    $val->inventory_turnover = -1;
                } elseif ($val->total_inventory == 0 && $val->week_daysales != 0) {
                    $val->inventory_turnover = 0;
                } else {
                    $val->inventory_turnover = round($val->total_inventory / $val->week_daysales / $val->plan_multiple);
                }

                //补货建议
                $val->courier = 0;//补货建议快递
                $val->air = 0;//补货建议空运
                $val->shipping = 0;//补货建议海运

                $ReplenData['sales_status'] = $val->sales_status;
                $ReplenData['this_weekDaysales'] = $this_weekDaysales; //近1周日销
                $ReplenData['plan_multiple'] = $val->plan_multiple; //销售计划增长倍数
                $ReplenData['total_inventory'] = $val->total_inventory; //total_inventory
                $ReplenData['inventory_turnover'] = $val->inventory_turnover; //在库可销售天数
                $ReplenData['courier'] = 0; //快递
                $ReplenData['week_daysales'] = $val->week_daysales; //近2周日销
                $ReplenData['this_monthDaysales'] = $this_monthDaysales; //近1个月日销


                $Replen = $this->getReplen($ReplenData);
                $val->courier = $Replen['courier'];//补货建议快递
                $val->air = $Replen['air'];//补货建议空运
                $val->shipping = $Replen['shipping'];//补货建议海运
                $val->replenishment_total = $Replen['replenishment_total'];//补货合计
            }
            return $skuData[0];
        }

    }

    //根据sku获取补货数据
    public function get_buhuo_detail_b($sku)
    {
        $day = date('d');
        $lastDay = 30;
        $year = date('Y');
        $month = date('m');
        $daySum = 14;
        $thisMonthSum = $lastDay;
        $thisDaySum = 7;
        //上周
        $startTime = date('Y-m-d 00:00:00', strtotime('-8 days',strtotime($year.'-'.$month.'-'.$day)));
        $endTime = date('Y-m-d 00:00:00', strtotime('-1 days',strtotime($year.'-'.$month.'-'.$day)));
        //上上周
        $startTimeTwo = date('Y-m-d 00:00:00', strtotime('-15 days',strtotime($year.'-'.$month.'-'.$day)));
        $endTimeTwo = date('Y-m-d 00:00:00', strtotime('-8 days',strtotime($year.'-'.$month.'-'.$day)));

        $startTimeMonth = date('Y-m-d 00:00:00', strtotime("-{$lastDay} days",strtotime($year.'-'.$month.'-'.$day)));
        $endTimeMonth = $endTime;


        $self_sku = DB::table('self_sku')->where('sku',$sku)->orWhere('old_sku',$sku)->select()->get()->toArray();
        if(empty($self_sku)){
            $amazon_skulist = DB::table('amazon_skulist')->where('sku',$sku)->select()->get()->toArray();
            $skuData = $amazon_skulist;
        }else{
            $skuData = $self_sku;
        }
        if (!empty($skuData)) {
            foreach ($skuData as $val) {
                //运营
                $val->account = '';
                $account = $this->GetUsers($val->user_id);
                if($account){
                    $val->account = $account['account'];
                }
                //店铺
                $val->shop_name = '';
                $shop_name = $this->GetShop($val->shop_id);
                if($shop_name){
                    $val->shop_name = $shop_name['shop_name'];
                }

                $custom_sku = $val->custom_sku;
                $img =  DB::table('self_custom_sku')->where('custom_sku',$custom_sku)->orWhere('old_custom_sku',$custom_sku)->select('img','old_custom_sku')->first();
                if(!empty($img)){
                    $img = json_decode(json_encode($img),true);
                    $val->img = $img['img'];
                    if(!empty($img['old_custom_sku'])){
                        $val->custom_sku = $img['old_custom_sku'];
                    }
                }
                //库存
                $val->tongAn_inventory = null;//同安仓库存
                $val->in_warehouse_inventory = null;//fba在仓库存
                $val->reserved_inventory = null;//预留库存
                $val->in_road_inventory = null;//在途库存
                $val->tongAn_deduct_inventory = null;//同安仓预扣库存

                $inventory = $this->getInventoryBySku($sku, $custom_sku);

                $val->tongAn_inventory = $inventory['tongAn_inventory'] ?? 0;
                $val->in_warehouse_inventory = $inventory['in_warehouse_inventory'] ?? 0;
                $val->reserved_inventory = $inventory['reserved_inventory'] ?? 0;
                $val->in_road_inventory = $inventory['in_road_inventory'] ?? 0;
                $val->fnsku = $inventory['fnsku'];
                $val->total_inventory = $val->in_warehouse_inventory + $val->reserved_inventory + $val->in_road_inventory;

                $tongAn_deduct_inventory = $this->getDeductInventory($custom_sku) ?? 0;
                if ($tongAn_deduct_inventory > 0) {
                    //如果该sku存在计划发货数量则扣除
                    $val->tongAn_deduct_inventory = $val->tongAn_inventory - $tongAn_deduct_inventory;
                } else {
                    //如果不存在计划发货数量则等于同安仓库存
                    $val->tongAn_deduct_inventory = $val->tongAn_inventory;
                }

                if(isset($val->old_sku)){
                    $wholeParams['old_sku'] = $val->old_sku;
                }
                $wholeParams['sku'] = $sku;
                //销量
                //上周销量
                $wholeParams['start_time'] = $startTime;
                $wholeParams['end_time'] = $endTime;
                $dataWhole = $this->getDatawholeByOtherNew($wholeParams);
                $val->quantity_ordered = $dataWhole;
                //上两周销量
                $wholeParams['start_time'] = $startTimeTwo;
                $wholeParams['end_time'] = $endTimeTwo;
                $dataWholeTwo = $this->getDatawholeByOtherNew($wholeParams);
                $val->before_quantity_ordered = $dataWholeTwo;

                //近一月合计销量
                $wholeParams['start_time'] = $startTimeMonth;
                $wholeParams['end_time'] = $endTimeMonth;
                $dataWholeMoth = $this->getDatawholeByOtherNew($wholeParams);
                $month_total = $dataWholeMoth;
                //根据sku找去年销量
                $val->lastyear_sales = 0;
                $lastYear = date('Y') - 1;
                $lastYearSql = "select `total_sales` from amazon_year_sale where `sku`='{$sku}' and `year`='{$lastYear}'";
                $lastYearData = DB::select($lastYearSql);
                if (!empty($lastYearData)) $val->lastyear_sales = $lastYearData[0]->total_sales;
                $val->last_year_daySales = round($val->lastyear_sales / 365, 2);//去年日销

                //近两周合计销量
                $val->total_sales = $val->quantity_ordered + $val->before_quantity_ordered;
                //本周日销
                $val->this_week_daysales = 0;
                $this_weekDaysales = round($val->quantity_ordered / $thisDaySum, 2);
                if ($this_weekDaysales > 0) $val->this_week_daysales = $this_weekDaysales;
                //近两周日销
                $val->week_daysales = 0;
                //近一月日销
                $this_monthDaysales = round($month_total / $lastDay, 2);
                if ($val->total_sales != 0) $val->week_daysales = round(($val->total_sales) / $daySum, 2);

                //库存可周转天数
                if ($val->total_inventory != 0 && $val->week_daysales == 0) {
                    $val->inventory_turnover = 999;
                } elseif ($val->total_inventory == 0 && $val->week_daysales == 0) {
                    $val->inventory_turnover = -1;
                } elseif ($val->total_inventory == 0 && $val->week_daysales != 0) {
                    $val->inventory_turnover = 0;
                } else {
                    $val->inventory_turnover = round($val->total_inventory / $val->week_daysales / $val->plan_multiple);
                }

                //补货建议
                $val->courier = 0;//补货建议快递
                $val->air = 0;//补货建议空运
                $val->shipping = 0;//补货建议海运

                $ReplenData['sales_status'] = $val->sales_status;
                $ReplenData['this_weekDaysales'] = $this_weekDaysales; //近1周日销
                $ReplenData['plan_multiple'] = $val->plan_multiple; //销售计划增长倍数
                $ReplenData['total_inventory'] = $val->total_inventory; //total_inventory
                $ReplenData['inventory_turnover'] = $val->inventory_turnover; //在库可销售天数
                $ReplenData['courier'] = 0; //快递
                $ReplenData['week_daysales'] = $val->week_daysales; //近2周日销
                $ReplenData['this_monthDaysales'] = $this_monthDaysales; //近1个月日销


                $Replen = $this->getReplen($ReplenData);
                $val->courier = $Replen['courier'];//补货建议快递
                $val->air = $Replen['air'];//补货建议空运
                $val->shipping = $Replen['shipping'];//补货建议海运
                $val->replenishment_total = $Replen['replenishment_total'];//补货合计
            }
            return $skuData[0];
        }

    }

    //新增pdf
    public function add_pdf($params){
        $file = $params['file'];
        $time = time();
        $filename = $file->getClientOriginalName();
        $filename = "d" . $time . "_" . $filename;
        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension != 'pdf') {
            return ['type' => 'fail', 'msg' => '上传失败，不是pdf文件'];
        }
        if (file_exists("./admin/amazon_pdf/" . $filename)) {
            return ['type' => 'fail', 'msg' => '文件已存在'];
        } else {
            move_uploaded_file($file, "./admin/amazon_pdf/" . $filename);
            $path = "/admin/amazon_pdf/" . $filename;
        }
        $data['file_path'] = $path;
        $data['file_name'] = $filename;

        return [
            'type'=>'success',
            'data' => $data
        ];

    }
     //新增创货件信息
     public function create_goods($paramsres)
     {

         $request_id = $paramsres['request_id'];
//         if(!is_int($request_id)){
//             return ['type' => 'fail', 'msg' => '请填写正确的计划id号'];
//         }
         $request_id_json = substr(substr(json_encode(array("request_id" => "{$request_id}")), 1), 0, -1);
         $task_data = Db::table('tasks')
             ->where('ext', 'like', "%{$request_id_json}%")
             ->where('state','!=',2)
             ->where('is_deleted', 0)
             ->whereIn('class_id', [2, 3, 4, 124])
             ->select('Id', 'name', 'user_fz','class_id')
             ->get()
             ->toArray();
         if ($task_data) {
             $task_id = $task_data[0]->Id;
         }
         $task_son = Db::table('tasks_son')->select('Id', 'user_id','state')->where(['task_id' => $task_id])->where('task','创货件')->first();
         if(empty($task_son)){
             return ['type' => 'fail', 'msg' => '任务流程中没有此任务'];
         }
         if($task_son->state==1){
             return ['type' => 'fail', 'msg' => '请先接受创货件任务'];
         }
         $taskArr['Id'] = $task_son->Id;

         $taskArr['state'] = 3;
         $taskArr['feedback_type'] = 1;
         $call_task = new \App\Libs\wrapper\Task();
         $selectGoods = DB::table('amazon_create_goods')->where('request_id', '=', $request_id)->select('id')->first();

         if (!empty($selectGoods)) {
             return ['type' => 'fail', 'msg' => '此计划已创货件,请勿重新创建'];
         }
         $selectPlan = DB::table('amazon_buhuo_request')->where('id', '=', $request_id)->select('id', 'shop_id', 'request_userid', 'request_status', 'courier_date', 'shipping_date', 'air_date')->get();

         if ($selectPlan->isEmpty()) {
             return ['type' => 'fail', 'msg' => '没有此计划,请重新填写'];
         }
         if ($selectPlan[0]->request_status < 6) {
             return ['type' => 'fail', 'msg' => '未装箱，不能创货件'];
         }
         $shop_id = $selectPlan[0]->shop_id;
         $user_id = $selectPlan[0]->request_userid;


         $insert = array();
         $date = date('Y-m-d H:i:s');
         if($paramsres['type']==1){
             foreach ($paramsres['data'] as  $k=>$params) {
                 # code...
                 if (!empty($params['serial_no'])) {
                     $serial_no = $params['serial_no'];
                     if(!preg_match("/^(([a-z]+[0-9]+)|([0-9]+[a-z]+))[a-z0-9]*$/i",$serial_no)){
                         return ['type' => 'fail', 'msg' => '货件编号必须由数字和字母的组合而成'];
                     }
                 }else{
                     return ['type' => 'fail', 'msg' => '请填写货件编号'];
                 }
                 if (!empty($params['tracking_no'])){
                     $tracking_no = $params['tracking_no'];
                     if(!preg_match("/^(([a-z]+[0-9]+)|([0-9]+[a-z]+))[a-z0-9]*$/i",$tracking_no)){
                         return ['type' => 'fail', 'msg' => '货件追踪码必须由数字和字母的组合而成'];
                     }
                 }else{
                     return ['type' => 'fail', 'msg' => '请填写货件追踪号'];
                 }
                 if(empty($params['center_id'])){
                     return ['type' => 'fail', 'msg' => '请填写仓库代号'];
                 }
                 if(empty($params['shipping_address'])){
                     return ['type' => 'fail', 'msg' => '请填写配送地址'];
                 }
                 $box_ids = $params['box_ids'];
                 if (!empty($box_ids)) {
                     if (strstr($box_ids, '，')) {
                         return ['type' => 'fail', 'msg' => '添加失败，箱号请用英文逗号分隔'];
                     }
                     $boxarray = explode(',',$box_ids);
                     $boxcount = count($boxarray);
                 }else{
                     return ['type' => 'fail', 'msg' => '请填写箱号'];
                 }

                 if ($request_id == null || $serial_no == null || $tracking_no == null || $box_ids == null) {
                     return ['type' => 'fail', 'msg' => '添加失败，参数不足，请填写完整'];
                 }
                 $insert[$k]['request_id'] = $request_id;
                 $insert[$k]['serial_no'] = $serial_no;
                 $insert[$k]['tracking_no'] = $tracking_no;
                 $insert[$k]['DestinationFulfillmentCenterId'] = $params['center_id'];
                 $insert[$k]['shipping_address'] = $params['shipping_address'];
                 $insert[$k]['time'] = $date;
                 $insert[$k]['box_ids'] = $box_ids;
                 $insert[$k]['shop_id'] = $shop_id;
                 $insert[$k]['user_id'] = $user_id;
                 $insert[$k]['type'] = $paramsres['type'];
                 $redis_json = json_encode(['shop_id' => $shop_id,'shippment_id' => $serial_no,'page_size'=>$boxcount]);
                 Redis::Lpush('creategoods_pdf', $redis_json);
             }
             $create = DB::table('amazon_create_goods')->insert($insert);
             if ($create) {
                 $return = $call_task->task_son_complete($taskArr);
                 if ($return == 1) {
                     $update_date_data['delivery_date'] = date('Y-m-d');
                     if ($selectPlan[0]->courier_date != '1970-01-01') $update_date_data['courier_date'] = date("Y-m-d", strtotime("+5 day"));
                     if ($selectPlan[0]->shipping_date != '1970-01-01') $update_date_data['shipping_date'] = date("Y-m-d", strtotime("+30 day"));
                     if ($selectPlan[0]->air_date != '1970-01-01') $update_date_data['air_date'] = date("Y-m-d", strtotime("+15 day"));
                     $update_date_data['request_status'] = 7;
                     Db::table('amazon_buhuo_request')->where('id', $selectPlan[0]->id)->update($update_date_data);
                 } else {
                     return ['type' => 'fail', 'msg' => '已加入采集队列，任务自动完成失败,请手动去我的任务完成'];
                 }
             } else {
                 return ['type' => 'fail', 'msg' => '创货件失败'];
             }
             return ['type' => 'success', 'msg' => '已加入采集队列，请稍后查看采集状态'];

         }else{
             if (empty($paramsres['serial_no'])) {
                 return ['type' => 'fail', 'msg' => '请填写货件编号'];
             }
             if (empty($paramsres['file_path'])) {
                 return ['type' => 'fail', 'msg' => '请上传箱唛'];
             }
             $insert['request_id'] = $request_id;
             $insert['serial_no'] = $paramsres['serial_no'];
             $insert['time'] = $date;
             $insert['shop_id'] = $shop_id;
             $insert['user_id'] = $user_id;
             $insert['type'] = $paramsres['type'];
             $insert['sprider_pdf_status'] = 1;
             $create = DB::table('amazon_create_goods')->insert($insert);
             if ($create) {
                 $return = $call_task->task_son_complete($taskArr);
                 if ($return == 1) {
                     $update_date_data['delivery_date'] = date('Y-m-d');
                     if ($selectPlan[0]->courier_date != '1970-01-01') $update_date_data['courier_date'] = date("Y-m-d", strtotime("+5 day"));
                     if ($selectPlan[0]->shipping_date != '1970-01-01') $update_date_data['shipping_date'] = date("Y-m-d", strtotime("+30 day"));
                     if ($selectPlan[0]->air_date != '1970-01-01') $update_date_data['air_date'] = date("Y-m-d", strtotime("+15 day"));
                     $update_date_data['request_status'] = 7;
                     Db::table('amazon_buhuo_request')->where('id', $selectPlan[0]->id)->update($update_date_data);
                 } else {
                     return ['type' => 'fail', 'msg' => '已创货件，但任务自动完成失败,请手动去我的任务完成'];
                 }
             } else {
                 return ['type' => 'fail', 'msg' => '创货件失败'];
             }
             return ['type' => 'success', 'msg' => '创货件成功'];
         }
     }


    //查询创货件信息
    public function select_createGoods($params)
    {
        $where = "1=1";
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $page = $this->getLimitParam($page, $limit);
        if (!empty($params['request_id'])) {
            $where .= " and request_id like '%{$params['request_id']}%'";
        }
        if (!empty($params['name'])) {
            $where .= " and file_name like '%{$params['name']}%'";
        }
        if (!empty($params['serial_no'])) {
            $where .= " and serial_no like '%{$params['serial_no']}%'";
        }
        if (!empty($params['tracking_no'])) {
            $where .= " and tracking_no like '%{$params['tracking_no']}%'";
        }
        if (!empty($params['store_id'])) {
            $where .= " and a.shop_id = {$params['store_id']}";
        }
        if (!empty($params['user_id'])) {
            $where .= " and user_id = {$params['user_id']}";
        }
        if (!empty($params['time'])) {
            $start_time = $params['time'][0] . ' 00:00:00';
            $end_time = $params['time'][1] . ' 23:59:59';
            $where .= " and time between '{$start_time}' and '{$end_time}'";
        }
        $sql = "SELECT SQL_CALC_FOUND_ROWS a.*,s.shop_name,u.account
                FROM
                    amazon_create_goods a
                LEFT JOIN 
                    shop s ON a.shop_id=s.Id 
                LEFT JOIN 
                    users u ON a.user_id=u.Id   
                WHERE
                    $where
                ORDER BY
                    id desc LIMIT $page,$limit";

        $data = DB::select($sql);
        $totalNum = db::select("SELECT FOUND_ROWS() as total")[0]->total;
        foreach ($data as $v) {
            # code...
            $requset_id = $v->request_id;
            $quantity_received = db::table('amazon_create_goods_receive')->where('request_id',$requset_id)->where('serial_no',$v->serial_no)->sum('quantity_received');
            $v->quantity_received = 0;
            if($quantity_received){
                $v->quantity_received = $quantity_received;
            }
        }
        return [
            'data' => $data,
            'totalNum' => $totalNum
        ];
    }

    //修改创货件信息
    public function update_createGoods($paramsres)
    {
        if (!empty($paramsres['request_id'])) $request_id = $paramsres['request_id'];
        $selectPlan = DB::table('amazon_buhuo_request')->where('id', '=', $request_id)->select('id','shop_id')->first();
        if (empty($selectPlan)) {
            return ['type' => 'fail', 'msg' => '没有此计划,请重新填写'];
        }
        $shop_id = $selectPlan->shop_id;
        $time = time();
        if($paramsres['type']==1) {
            DB::table('amazon_create_goods')->where('request_id',$request_id)->delete();
            foreach ($paramsres['data'] as $params) {
                // if (!empty($params['id'])) {
                //     $id = $params['id'];
                //     $goods = DB::table('amazon_create_goods')->where('id', '=', $id)->select('DestinationFulfillmentCenterId', 'shipping_address', 'serial_no', 'tracking_no', 'box_ids')->first();
                //     if (!empty($params['serial_no'])) {
                //         $serial_no = $params['serial_no'];
                //         if (!preg_match("/^(([a-z]+[0-9]+)|([0-9]+[a-z]+))[a-z0-9]*$/i", $serial_no)) {
                //             return ['type' => 'fail', 'msg' => '货件编号必须由数字和字母的组合而成'];
                //         }
                //     } else {
                //         return ['type' => 'fail', 'msg' => '请填写货件编号'];
                //     }
                //     if (!empty($params['tracking_no'])) {
                //         $tracking_no = $params['tracking_no'];
                //         if (!preg_match("/^(([a-z]+[0-9]+)|([0-9]+[a-z]+))[a-z0-9]*$/i", $serial_no)) {
                //             return ['type' => 'fail', 'msg' => '货件追踪号必须由数字和字母的组合而成'];
                //         }
                //     } else {
                //         return ['type' => 'fail', 'msg' => '请填写货件追踪号'];
                //     }
    
                //     if (empty($params['center_id'])) {
                //         return ['type' => 'fail', 'msg' => '请填写仓库代号'];
                //     }
                //     if (empty($params['shipping_address'])) {
                //         return ['type' => 'fail', 'msg' => '请填写配送地址'];
                //     }
                //     $box_ids = $params['box_ids'];
                //     if (!empty($params['box_ids'])) {
                //         if (strstr($params['box_ids'], '，')) {
                //             return ['type' => 'fail', 'msg' => '修改失败，箱号请用英文逗号分隔'];
                //         }
                //         $boxarray = explode(',', $box_ids);
                //         $boxcount = count($boxarray);
                //     } else {
                //         return ['type' => 'fail', 'msg' => '请填写箱号'];
                //     }
                //     if ($request_id == null || $serial_no == null || $tracking_no == null || $box_ids == null) {
                //         return ['type' => 'fail', 'msg' => '修改失败，参数不足，请填写完整'];
                //     }
                //     $update = array();
                //     if ($goods->serial_no != $serial_no) {
                //         $update['serial_no'] = $serial_no;
                //         $redis_json = json_encode(['shop_id' => $shop_id, 'shippment_id' => $serial_no, 'page_size' => $boxcount]);
                //         Redis::Lpush('creategoods_pdf', $redis_json);
                //     }
                //     if ($goods->tracking_no != $tracking_no) $update['tracking_no'] = $tracking_no;
                //     if ($goods->DestinationFulfillmentCenterId != $params['center_id']) $update['DestinationFulfillmentCenterId'] = $params['center_id'];
                //     if ($goods->shipping_address != $params['shipping_address']) $update['shipping_address'] = $params['shipping_address'];
                //     if ($goods->box_ids != $box_ids) {
                //         $update['box_ids'] = $box_ids;
                //         $redis_json = json_encode(['shop_id' => $shop_id, 'shippment_id' => $serial_no, 'page_size' => $boxcount]);
                //         Redis::Lpush('creategoods_pdf', $redis_json);
                //     }
                //     $update['update_time'] = $time;
                //     $update = DB::table('amazon_create_goods')->where('id', '=', $id)->update($update);
                //     if (!$update) {
                //         return ['type' => 'fail', 'msg' => '修改失败，未知错误'];
                //     }
                // } else {
                    if (!empty($params['serial_no'])) {
                        $serial_no = $params['serial_no'];
                        if (!preg_match("/^(([a-z]+[0-9]+)|([0-9]+[a-z]+))[a-z0-9]*$/i", $serial_no)) {
                            return ['type' => 'fail', 'msg' => '货件编号必须由数字和字母的组合而成'];
                        }
                    } else {
                        return ['type' => 'fail', 'msg' => '请填写货件编号'];
                    }
                    if (!empty($params['tracking_no'])) {
                        $tracking_no = $params['tracking_no'];
                        if (!preg_match("/^(([a-z]+[0-9]+)|([0-9]+[a-z]+))[a-z0-9]*$/i", $serial_no)) {
                            return ['type' => 'fail', 'msg' => '货件追踪号必须由数字和字母的组合而成'];
                        }
                    } else {
                        return ['type' => 'fail', 'msg' => '请填写货件追踪号'];
                    }
    
                    if (empty($params['center_id'])) {
                        return ['type' => 'fail', 'msg' => '请填写仓库代号'];
                    }
                    if (empty($params['shipping_address'])) {
                        return ['type' => 'fail', 'msg' => '请填写配送地址'];
                    }
                    $box_ids = $params['box_ids'];
                    if (!empty($params['box_ids'])) {
                        if (strstr($params['box_ids'], '，')) {
                            return ['type' => 'fail', 'msg' => '修改失败，箱号请用英文逗号分隔'];
                        }
                        $boxarray = explode(',', $box_ids);
                        $boxcount = count($boxarray);
                    } else {
                        return ['type' => 'fail', 'msg' => '请填写箱号'];
                    }
                    if ($request_id == null || $serial_no == null || $tracking_no == null || $box_ids == null) {
                        return ['type' => 'fail', 'msg' => '修改失败，参数不足，请填写完整'];
                    }
                    $insert = array();
                    $insert['serial_no'] = $serial_no;
                    $insert['box_ids'] = $box_ids;
                    $insert['tracking_no'] = $tracking_no;
                    $insert['DestinationFulfillmentCenterId'] = $params['center_id'];
                    $insert['shipping_address'] = $params['shipping_address'];
                    $redis_json = json_encode(['shop_id' => $shop_id, 'shippment_id' => $serial_no, 'page_size' => $boxcount]);
                    Redis::Lpush('creategoods_pdf', $redis_json);
                    $insert['update_time'] = $time;

                    $selectPlan = DB::table('amazon_buhuo_request')->where('id', '=', $request_id)->select('id', 'shop_id', 'request_userid', 'request_status', 'courier_date', 'shipping_date', 'air_date')->get();

                    if ($selectPlan->isEmpty()) {
                        return ['type' => 'fail', 'msg' => '没有此计划,请重新填写'];
                    }
                    if ($selectPlan[0]->request_status < 6) {
                        return ['type' => 'fail', 'msg' => '未装箱，不能创货件'];
                    }
                    $shop_id = $selectPlan[0]->shop_id;
                    $user_id = $selectPlan[0]->request_userid;
                    $date = date('Y-m-d H:i:s');
                    $insert['time'] = $date;
                    $insert['shop_id'] = $shop_id;
                    $insert['user_id'] = $user_id;
                    $insert['request_id'] = $request_id;
                    $insert['type'] = 1;
                    DB::table('amazon_create_goods')->insert($insert);
                // }
              
            }
            return ['type' => 'success', 'msg' => '修改成功，稍后将重新采集'];
        }else{
            if (empty($paramsres['serial_no'])) {
                return ['type' => 'fail', 'msg' => '请填写货件编号'];
            }
            if(empty($paramsres['file_path'])){
                return ['type' => 'fail', 'msg' => '请上传箱唛'];
            }
            $update['update_time'] = $time;
            $update['serial_no'] = $paramsres['serial_no'];
            $update['file_path'] = $paramsres['file_path'];
            $update['sprider_pdf_status'] = 1;
            $update = DB::table('amazon_create_goods')->where('id', '=', $paramsres['id'])->update($update);
            if (!$update) {
                return ['type' => 'fail', 'msg' => '修改失败，未知错误'];
            }
            return ['type' => 'success', 'msg' => '修改成功'];
        }
    }

    //保存装箱数据
    public function save_box_data($params)
    {
        $count = isset($params['count']) ? $params['count'] : 1;
        $data1 = isset($params['data1']) ? $params['data1'] : null;
        $data2 = isset($params['data2']) ? $params['data2'] : null;
        $request_id = $data1[0]['request_id'];
        if ($params['request_status']<4){
            return ['type' => 'fail', 'msg' => '状态异常，无法装箱'];
        }

        $user_id = $this->GetUserIdByToken($params['token']);
        $request_id_json = substr(substr(json_encode(array("request_id" => "{$request_id}")), 1), 0, -1);
        $task_data = Db::table('tasks')
            ->where('ext', 'like', "%{$request_id_json}%")
            ->where('state','!=',2)
            ->whereIn('class_id', [2, 3, 4, 124])
            ->where('is_deleted', 0)
            ->select('Id', 'name', 'user_fz','class_id')
            ->get()
            ->toArray();
        if ($task_data) {
            $task_id = $task_data[0]->Id;
        } else {
            return ['type' => 'fail', 'msg' => '该计划未发布任务，tasks表'];
        }


        //判断补货类型
        $request_res = db::table('amazon_buhuo_request')->where('id',$request_id)->first();
        if(!$request_res){
            return ['type' => 'fail', 'msg' => '无该补货计划'];
        }

        if($request_res->request_status>7){
            return ['type' => 'fail', 'msg' => '该状态无法修改'];
        }

        if($request_res->request_type==2){
            //工厂直发  只有数据复核人可以修改  已创货件待装箱时
            if($request_res->request_status==7){
                $task_node = db::table('tasks_node')->where('task_id', $task_id)->where('name','数据复核')->first();

                if(!$task_node){
                    return ['type' => 'fail', 'msg' => '工厂直发需数据复核，该任务无数据复核'.$task_id];
                }
    
                $task_son = Db::table('tasks_son')->where('tasks_node_id',$task_node->Id)->first();
                if(!$task_son){
                    return ['type' => 'fail', 'msg' => '工厂直发需数据复核，该任务无数据复核人'.$task_id];
                }
          
                $sjfh_user_id =  $task_son->user_id;
                $sjfh_user = $this->GetUsers($sjfh_user_id)['account'];
    
                if($sjfh_user_id!=$user_id){
                    return ['type' => 'fail', 'msg' => '数据复核人'.$sjfh_user.'才可以修改装箱数据'];
                }
            }

        }


      


        $task_son = Db::table('tasks_son')
            ->select('Id', 'user_id','state','day_yj')
            ->where(['task_id' => $task_id])
            ->get()
            ->toArray();

        if($task_data[0]->class_id!=124){
            if($task_son[0]->state==1) return ['type' => 'fail', 'msg' => '请先接受拣货装箱任务'];
        }




        $taskArr['Id'] = $task_son[0]->Id;

        $taskArr['state'] = 3;
        $taskArr['feedback_type'] = 1;
        $call_task = new \App\Libs\wrapper\Task();

        db::beginTransaction();    //开启事务
        if ($data1 != null) {
            // 可优化，取new_custom_sku
            $customSku = array_column($data1, 'custom_sku');
//            $groupSkuArr = [];
//            foreach ($customSku as $item){
//                $customSkuMdl = $this->customSkuModel::query()
//                    ->where(function ($query) use ($item){
//                        return $query->where('custom_sku', $item)
//                            ->orWhere('old_custom_sku', $item);
//                    })
//                    ->first();
//                if (!empty($customSkuMdl->id) && $customSkuMdl->type == 2){
//
//                    $groupSkuCount = $this->groupCustomSkuModel::query()
//                        ->where('custom_sku_id', $customSkuMdl->id)
//                        ->count();
//                    $groupSkuArr[$item] = $groupSkuCount;
//                }
//            }

            $if_up = false;
            if ($data2 != null) {
                $box_type = ['heavy', 'long', 'wide', 'high'];
                foreach ($data2 as $key2 => $val2) {
                    for ($k = 1; $k <= $count; $k++) {
                        $str2 = 'number' . $k;
                        if (isset($val2[$str2])) {
                            $boxTypeDetail[$box_type[$key2]][$k] = $val2[$str2];
                        } else {
                            db::rollback();// 回调
                            return ['type' => 'fail', 'msg' => '装箱错误，请重新录入'];
                        }
                    }
                }
            }
            $custom_sku_box = [];
            $groupCustomSkuMdl = db::table('self_custom_sku as a')
                ->leftJoin('self_group_custom_sku as b', 'a.id', '=', 'b.custom_sku_id')
                ->where('a.type', 2)
                ->select('a.id', db::raw('count(b.id) as count'))
                ->groupBy('a.id')
                ->get()
                ->keyBy('id');
            $boxItemDetail = [];
            foreach ($data1 as $val1) {


                $detail_box = DB::table('amazon_buhuo_detail')->where('id', '=', $val1['id'])->select('box_data_detail')->first()->box_data_detail;

                $detail_box_detail = json_decode($detail_box,true);

                for ($i = 1; $i <= $count; $i++) {
                    $str = 'number' . $i;
                    if(isset($val1[$str])){
                        $boxNum = $val1[$str];

                        $update_time = date('Y-m-d H:i:s',time());
                        //如果和数据库不一样则为修改数据，加入日志
                        if(isset($detail_box_detail[$i - 1])){
                            if($detail_box_detail[$i - 1]!=$boxNum){
                                db::table('amazon_buhuo_box_log')->insert(['request_id'=>$request_id,'box_no'=>$i-1,'num'=>$boxNum,'user_id'=>$user_id,'sku_id'=>$val1['sku_id'],'update_time'=>$update_time,'old_num'=>$detail_box_detail[$i - 1],'type'=>1,'sku'=>$val1['sku']]);
                                //修改了装箱数据，需要发送站内信  2023.11.30 9:46简雪琴修改了装箱数据，请尽快查看是否需要重新创建货件
                                $if_up = true;
                            }
                        }else{
                            db::table('amazon_buhuo_box_log')->insert(['request_id'=>$request_id,'box_no'=>$i-1,'num'=>$boxNum,'user_id'=>$user_id,'sku_id'=>$val1['sku_id'],'update_time'=>$update_time,'old_num'=>0,'type'=>2,'sku'=>$val1['sku']]);
                            $if_up = true;
                        }


                        $sku_num[$i - 1] = $boxNum;
                        $sku_arr[$val1['sku']][$i - 1] = $boxNum;
                        if(isset($custom_sku_arr[$val1['custom_sku']][$i - 1])){
                            $custom_sku_arr[$val1['custom_sku']][$i - 1] += $boxNum;
                        }else{
                            $custom_sku_arr[$val1['custom_sku']][$i - 1] = $boxNum;
                        }

                        $actual_num = $boxNum;
                        if (isset($groupCustomSkuMdl[$val1['custom_sku_id']])){
                            $actual_num = $boxNum * $groupCustomSkuMdl[$val1['custom_sku_id']]->count;
                        }
                        $boxItemDetail[] = [
                            'request_id' => $val1['request_id'],
                            'status' => 1,
                            'box_no' => $i,
                            'custom_sku_id' => $val1['custom_sku_id'],
                            'custom_sku' => $val1['custom_sku'],
                            'spu_id' => $val1['spu_id'],
                            'spu' => $val1['spu'],
                            'user_id' => $user_id,
                            'num' => $boxNum,
                            'actual_num' => $actual_num,
                            'long' => $boxTypeDetail['long'][$i],
                            'wide' => $boxTypeDetail['wide'][$i],
                            'high' => $boxTypeDetail['high'][$i],
                            'heavy' => $boxTypeDetail['heavy'][$i],
                            'created_at' => date('Y-m-d H:i:s', microtime(true)),
                            'shop_id' => $val1['shop_id'],
                            'sku' => $val1['sku'],
                            'sku_id' => $val1['sku_id'],
                            'cus_box_id' => $val1['cus_box_id']
                        ];
                    }else{
                        return ['type' => 'fail', 'msg' => '装箱错误，请重新录入'];
                    }
                }


                $num = json_encode($sku_num);
                $detail_update = DB::table('amazon_buhuo_detail')->where('id', '=', $val1['id'])->update(['box_data_detail' => $num]);
//                if(!$detail_update){
//                    db::rollback();// 回调
//                    return ['type' => 'fail', 'msg' => '保存失败,amazon_buhuo_detail表'];
//                }


            }



            //如果修改了数据   并且是工厂直发类型  并且状态是已创货件  则发站内信
            if($if_up){
                if($request_res->request_type==2){
                    //工厂直发  只有数据复核人可以修改  已创货件待装箱时
                    if($request_res->request_status==7){
    
                        //修改了装箱数据，需要发送站内信 2023.11.30 9:46简雪琴修改了装箱数据，请尽快查看是否需要重新创建货件
                        $msg_data['user_fs'] = $user_id;
                        $account = $this->GetUsers($user_id)['account'];
                        $msg_data['send_type'] = 1;//1站内信
                        $msg_data['content'] = $update_time.' '.$account.'修改了装箱数据，请尽快查看是否需要重新创建货件';
                        $msg_data['task_name'] = $task_data[0]->name;
                        $msg_data['task_id'] = $task_id;
                        $msg_data['user_js'][0] = $task_data[0]->user_fz;
                        $msg_data['msg_type'] = 1;
    
                        $call_task = new \App\Libs\wrapper\Task();
                        $return = $call_task->task_new_add($msg_data);
                        if($return!=1){
                            db::rollback();// 回调
                            return ['type' => 'fail', 'msg' => '发送站内信失败'.json_encode($msg_data)];
                        }
    
                    }
                }
            }
  


            $box_all_total = 0;//装箱总数

            for ($j = 0; $j < $count; $j++) {
//                foreach ($sku_arr as $k1 => $v1) {
//                    $box_num[$k1] = $v1[$j];
//                }
                foreach ($custom_sku_arr as $k1 => $v1){
                    $box_num[$k1] = $v1[$j];
//                    if (array_key_exists($k1, $groupSkuArr)){
//                        $box_num[$k1] = $v1[$j] * $groupSkuArr[$k1];
//                    }
                }
                $box_total[$j] = array_sum($box_num);
                $box_all_total += $box_total[$j];
            }
            $goods_transfers_box = DB::table('goods_transfers_box')
                ->where('order_no',$request_id)
                ->select('onshelf_num')->first();

            if($task_data[0]->class_id!=124){
                if(!empty($goods_transfers_box)){
                    if($goods_transfers_box->onshelf_num!=$box_all_total){
                        return ['type' => 'fail', 'msg' => '装箱数据与下架数据不一致，请核查下架明细'];
                    }
                }else{
                    return ['type' => 'fail', 'msg' => '未获取到出库任务号'];
                }
            }
        } else {
            db::rollback();// 回调
            return ['type' => 'fail', 'msg' => '没有装箱数据'];
        }

        if ($data2 != null) {
            foreach ($data2 as $key2 => $val2) {
                for ($k = 1; $k <= $count; $k++) {
                    $str2 = 'number' . $k;
                    if(isset($val2[$str2])){
                        $box_data[$k - 1] = $val2[$str2];
                        $box_arr[$key2][$k - 1] = $val2[$str2];
                    }else{
                        db::rollback();// 回调
                        return ['type' => 'fail', 'msg' => '装箱错误，请重新录入'];
                    }
                }
            }
            $time = time();
            //清空原有的装箱数据
            $delete = DB::table('amazon_box_data')->where('request_id', '=', $request_id)->delete();
            $delete = DB::table('amazon_box_data_detail')->where('request_id', '=', $request_id)->delete();
            foreach ($boxItemDetail as $d){
                $insert = db::table('amazon_box_data_detail')->insertGetId($d);
                if(!$insert){
                    db::rollback();// 回调
                    return ['type' => 'fail', 'msg' => '保存失败,amazon_box_data_detail表'];
                }
            }
            for ($x = 0; $x < $count; $x++) {
                foreach ($box_arr as $k2 => $v2) {
                    $box_param[$k2] = $v2[$x];
                }
                $insert = DB::table('amazon_box_data')->insert(['request_id' => $request_id, 'box_id' => $x + 1, 'heavy' => $box_param[0],
                'long' => $box_param[1], 'wide' => $box_param[2], 'high' => $box_param[3], 'box_num' => $box_total[$x], 'creat_time' => $time]);
                if(!$insert){
                    db::rollback();// 回调
                    return ['type' => 'fail', 'msg' => '保存失败,amazon_box_data表'];
                }
            }
        } else {
            db::rollback();// 回调
            return ['type' => 'fail', 'msg' => '没有装箱数据'];
        }
        if ($params['request_status'] <6) {
            $update_request = Db::table('amazon_buhuo_request')->where('id', $request_id)->update(['request_status' => 6]);
            if (!$update_request) {
                db::rollback();// 回调
                return ['type' => 'fail', 'msg' => '计划状态修改失败，amazon_buhuo_request表'];
            }
            if($task_data[0]->class_id!=124){
                $return = $call_task->task_son_complete($taskArr);
                if ($return == 1) {
                    if(isset($task2_id)){
                        $taskArr['Id'] = $task2_id;
                        $return2 = $call_task->task_son_complete($taskArr);
                        if(!$return2){
                            return ['type' => 'fail', 'msg' => '保存成功，备货任务自动完成失败,请手动去我的任务完成'];
                        }
                    }
                    db::commit();
                    return ['type' => 'success', 'msg' => '保存成功'];
                } else {
                    db::commit();
                    return ['type' => 'fail', 'msg' => '保存成功，但装箱任务自动完成失败,请手动去我的任务完成'];
                }
            }
        }
        db::commit();
        return ['type' => 'success', 'msg' => '保存成功'];

    }

    //补货计划导出
    public function request_excel_export($params)
    {
        $where = "a.request_status !=1";
        if (!empty($params['store_id'])) {
            $where .= " and s.Id={$params['store_id']}";
        }
        if (!empty($params['user_id'])) {
            $where .= " and u.Id={$params['user_id']}";
        }
        if (!empty($params['status_id'])) {
            $where .= " and a.request_status={$params['status_id']}";
        }
        if (!empty($params['plan_id'])) {
            $where .= " and a.id={$params['plan_id']}";
        }
        if (!empty($params['warehouse'])) {
            $where .= " and a.warehouse={$params['warehouse']}";
        }
        if (isset($params['start_time'])) {
            $time_start = $params['start_time'] . ' 00:00:00';
            $time_end = $params['end_time'] . ' 23:59:59';
            $where .= " and a.request_time between '{$time_start}' and '{$time_end}'";
        }


        $sql = "SELECT SQL_CALC_FOUND_ROWS
                    a.id,
                    s.shop_name,
                    a.delivery_date,
                    a.logistics_price,
                    a.logistics_order_no,      
                    a.calculate_heavy,
                    acg.file_name,
                    acg.serial_no,
                    acg.tracking_no,
                    acg.DestinationFulfillmentCenterId
                FROM
                    amazon_buhuo_request a
                LEFT JOIN shop s ON s.Id = a.shop_id
                LEFT JOIN amazon_create_goods acg on a.id=acg.request_id
                LEFT JOIN users u ON u.Id = a.request_userid
                WHERE
                    {$where}
                ORDER BY
                    a.id desc";

        $list = DB::select($sql);

        foreach ($list as $key => $val) {
            $request_id = $val->id;
            $detail = Db::table('amazon_box_data')->where('request_id', $request_id)->select('box_num')->get()->toArray();
            //取出所有box_data_detail字段的值组成数组
            $box_data_detail = array_column($detail, 'box_num');
            $list[$key]->num = array_sum($box_data_detail);
            //数量
//            if (!empty($box_data_detail)) {
//                //取出数组中的空值
//                $box_data = array_filter($box_data_detail);
//                if ($box_data) {
//                    $box_data = json_decode($box_data[0], true);
//                    //相加所有值
//                    $num = array_sum($box_data);
//                    $list[$key]->num = $num;
//                }
//
//            }

//            $box_data = Db::table('amazon_box_data')->where('request_id', $request_id)->get()->toArray();
//            //运费
//            //取出所有calculate_heavy字段的值组成数组
//            $calculate_heavy = array_column($box_data, 'calculate_heavy');
//            if (!empty($calculate_heavy)) {
//                //取出数组中的空值
//                $calculate_heavy_arr = array_filter($calculate_heavy);
//                if ($calculate_heavy_arr) {
//                    //相加所有值
            $heavy = $val->calculate_heavy;
            //运费=单价*重量
            $list[$key]->price = bcmul($val->logistics_price * $heavy, 2);
//                }
//
//            }
            //箱数
            $count = count($detail);
            $list[$key]->count = $count;
        }

        $list = json_decode(json_encode($list), true);

        foreach ($list as $k => $v) {
            $list[$k]['carrier'] = '';//承运商
            $list[$k]['destination_warehouse'] = isset($v['DestinationFulfillmentCenterId']) ? $v['DestinationFulfillmentCenterId'] : '';//目的地仓库
            $list[$k]['commodity'] = ''; //商品
            $list[$k]['num'] = isset($v['num']) ? $v['num'] : '';
            $list[$k]['calculate_heavy'] = isset($v['calculate_heavy']) ? $v['calculate_heavy'] : '';
            $list[$k]['price'] = isset($v['price']) ? $v['price'] : '';
            $list[$k]['fba'] = "货件名称：{$v['file_name']} 编号：{$v['serial_no']} 货件追踪编号：{$v['tracking_no']}";
        }

        //处理数据
        //表头
        $title = array(
            'shop_name' => '店铺',
            'delivery_date' => '发货日期',
            'carrier' => '承运商',
            'destination_warehouse' => '目的地仓库',
            'commodity' => '商品',
            'num' => '数量',
            'count' => '箱数',
            'calculate_heavy' => '重量',
            'price' => '运费',
            'logistics_order_no' => '运单号',
            'logistics_price' => '单件运费',
            'fba' => 'FBA#',
            'id' => '任务ID号'
        );
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S');
        $file_name = 'fba物流费用';
        $this->excel_export_api($title, $list, $cellName, $file_name);


    }

    //补货详情导出
    public function detailed_excel_export($params)
    {
        $plan_id = $params['plan_id'];
        $where = "request_id='$plan_id'";
        $sql = "SELECT 
                    a.sku,a.custom_sku,a.request_num, a.transportation_mode_name, a.transportation_type, a.box_data_detail, c.transportation_date
                FROM
                    amazon_buhuo_detail a 
                LEFT JOIN amazon_buhuo_request c ON a.request_id = c.id
                WHERE
                    $where
                ORDER BY
                    a.custom_sku desc";

        $list = DB::select($sql);

        if (!empty($list)) {

            foreach ($list as $val) {
                $val->num_sum = $val->request_num;
            }
        }

        $list = json_decode(json_encode($list), true);

        foreach ($list as $k => $v) {
            $box_data_arr =array();
            $box_data_detail = json_decode($v['box_data_detail'],true);
            if(!is_null($box_data_detail)){
                foreach ($box_data_detail as $boxVal){
                    $box_data_arr[] = $boxVal;
                }
            }
            $box_data_sum = array_sum($box_data_arr);

            if ($box_data_sum == 0) {
                $list[$k]['box_data_detail'] = '未装箱';
            }else{
                $list[$k]['box_data_detail'] = $box_data_sum;
            }
        }

        //处理数据
        //表头
//        $title = array(
//            'sku' => 'SKU',
//            'custom_sku' => '库存SKU',
//            'courier_num' => '补货数量(快递)',
//            'shipping_num' => '补货数量(海运)',
//            'air_num' => '补货数量(空运)',
//            'num_sum' => '补货数量(合计)',
//            'box_data_detail' => '实际发货数量'
//        );
        $title = array(
            'sku' => 'SKU',
            'custom_sku' => '库存SKU',
            'transportation_mode_name' => '运输方式',
            'request_num' => '补货数量',
            'num_sum' => '补货数量(合计)',
            'box_data_detail' => '实际发货数量'
        );
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I');
        $file_name = '补货单明细';
        $this->excel_export_api($title, $list, $cellName, $file_name);


    }

    //装箱单导出
    public function box_excel_export($params)
    {
        $plan_id = $params['plan_id'];
        $where = "request_id='$plan_id'";
        $sql = "SELECT SQL_CALC_FOUND_ROWS
                    a.sku,
                    a.custom_sku,
                    a.box_data_detail,
                    c.box_data,
                    0 as boxNum_sum
                FROM
                    amazon_buhuo_detail a 
                LEFT JOIN amazon_skulist b ON a.sku = b.sku
                LEFT JOIN amazon_buhuo_request c ON a.request_id = c.id
                WHERE
                    $where
                ORDER BY
                    a.custom_sku desc";

        $data = DB::select($sql);
//        if (empty($data)) {
//            return '没有装箱单数据';
//        }
        foreach ($data as $key => $val) {
            $in_box_num = '';
            if ($val->box_data_detail != '') {
                $in_box_num = json_decode($val->box_data_detail, true);
//                    $val->box_data_detail = array_sum($in_box_num);
            } /*else {
                $val->box_data_detail = 0;
            }*/
            $val->box_data_detail_arr = $in_box_num;
//                var_dump($val->box_data_detail);die;
            $data[$key]->num_sum = null;
            $arr = (array)($val);
            if ($in_box_num != '') {
                $num_count = 1;
                $num_arr = $in_box_num;
                if (is_array($num_arr)) {
                    //计算一共有多少个集装箱
                    $num_count = count($num_arr);
                }
//                    var_dump($num_count);die;
                //给每个集装箱附上以number开头的键值
                for ($j = 0; $j < $num_count; $j++) {
                    $str = "number" . ($j + 1);
                    $arr[$str] = $num_arr[$j];
                }
                $data[$key] = (object)($arr);
                $data[$key]->num_count = $num_count;
                if ($num_count == 1) {
                    $data[$key]->boxNum_sum = $num_arr[0];
                } else {
                    $data[$key]->boxNum_sum = array_sum($num_arr)[0];
                }

            }
        }


        //查找装箱单信息
        $box_data = DB::table('amazon_box_data')->where('request_id', '=', $plan_id)->select('calculate_heavy', 'heavy', 'long', 'wide', 'high', 'box_num')->get();
        $box = array();
        $calculate_heavy_arr = array();
        $heavy_sum = null;
        if (!empty($box_data)) {
            foreach ($box_data as $k => $v) {
                $str = "number" . ($k + 1);
                $calculate_heavy_arr[$k] = $v->calculate_heavy;
                $box[0][$str] = $v->calculate_heavy;
                $box[1][$str] = $v->heavy;
                $box[2][$str] = $v->long;
                $box[3][$str] = $v->wide;
                $box[4][$str] = $v->high;
                $box[0]['sku'] = '计费重量';
                $box[1]['sku'] = '重量';
                $box[2]['sku'] = '长度';
                $box[3]['sku'] = '宽度';
                $box[4]['sku'] = '高度';
                $box[0]['custom_sku'] = 'KG';
                $box[1]['custom_sku'] = 'KG';
                $box[2]['custom_sku'] = 'CM';
                $box[3]['custom_sku'] = 'CM';
                $box[4]['custom_sku'] = 'CM';
                $box[0]['boxNum_sum'] = '';
                $box[1]['boxNum_sum'] = '';
                $box[2]['boxNum_sum'] = '';
                $box[3]['boxNum_sum'] = '';
                $box[4]['boxNum_sum'] = '';
            }
        }

        $list = json_decode(json_encode(array_merge($data, $box)), true);
        $num_count_arr = array_column($list, 'num_count');
        $title_arr = [];
        if (!empty($num_count_arr)) {
            //计算最多的集装箱有几个
            $max = max($num_count_arr);

            for ($i = 1; $i <= $max; $i++) {
                $title_key = 'number' . $i;
//            $title_arr = [$title_key=>$i];
                $title_arr[$title_key] = $i . '号箱';
            }
        }
        $title = array(
            'sku' => '虚拟SKU',
            'boxNum_sum' => '合计',
            'custom_sku' => '库存SKU',
        );
        $title = array_merge($title, $title_arr);
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $file_name = '装箱单明细';
        $this->excel_export_api($title, $list, $cellName, $file_name);


    }

    //生产下单数据
    public function production_order($params)
    {
        $where = '';
        if (isset($params['style_no'])) {
            $where = "where style_no like '%{$params['style_no']}%'";
        }
        //分页
        $limit = "";
        if ((!empty($params['page'])) and (!empty($params['page_count']))) {
            $limit = " limit " . ($params['page'] - 1) * $params['page_count'] . ",{$params['page_count']}";
        }

        $sql = "SELECT SQL_CALC_FOUND_ROWS * 
                    FROM production_order 
                    {$where}
                ORDER BY
                    id asc {$limit}";
        $list = Db::select($sql);
        //总条数
        if (isset($params['page']) and isset($params['page_count'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }

        $return['list'] = $list;
        return $return;

    }

    //生产下单导入
    public function production_excel_export($params)
    {
        ////获取Excel文件数据
        //载入文档
        $objPHPExcelReader = \PHPExcel_IOFactory::load($params['file']['tmp_name']);
        $currentSheet = $objPHPExcelReader->getSheet(0);//读取第一个工作表(编号从 0 开始)
//		$allColumn = 'O';//取得总列数
        $allColumn = $currentSheet->getHighestColumn();//取得总列数
        $allRow = $currentSheet->getHighestRow();//取得总行数

        $add_list = array();
        /**从第1行开始输出*/
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            /**从第A列开始输出*/
            for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
                $key = $currentSheet->getCellByColumnAndRow((ord($currentColumn) - 65), 1)->getValue();//数据键值
                $val = $currentSheet->getCellByColumnAndRow((ord($currentColumn) - 65), $currentRow)->getValue();//数据
                $gva = $currentSheet->getCellByColumnAndRow((ord($currentColumn) - 65), $currentRow)->getFormattedValue();//数据

                if ($currentColumn == 'G') {
                    break;
                }
                //判断键名是否正确
                $array_key = array('款号', '下单', '出货');
                if (!in_array($key, $array_key)) {
                    return 'Excel数据格式不对,请下载Excel模板进行导入';
                }

                if ($key == '款号') {
                    $add_list[$currentRow - 2]['style_no'] = $val;
                } else if ($key == '下单') {
                    $add_list[$currentRow - 2]['order_num'] = empty($val) ? 0 : $val;
                } else if ($key == '出货') {
                    $add_list[$currentRow - 2]['shipment_num'] = empty($val) ? 0 : $val;
                }
            }
        }
//        var_dump($add_list);die;
        // 处理数据
        $list = array();
        //取出style_no字段并去除重复值
        $style_no = array_unique(array_column($add_list, 'style_no'));
        //查找production_order表中的数据
        $production_order = Db::table('production_order')->get()->toArray();

        foreach ($style_no as $key => $value) {
            $order_num = 0;
            $shipment_num = 0;
            // 通过循环导入数据$add_list中的style_no和$style_no数组对比 如果导入的数据$add_list中的style_no字段的值和取出的style_no字段组成的的数组的数据相同，则将导入数据中相同的数据相加
            foreach ($add_list as $k => $v) {
                if ($value == $v['style_no']) {
                    //将导入数据中的重复值相加
                    $order_num += $v['order_num'];
                    $shipment_num += $v['shipment_num'];
                }
            }
            //对比导入数据$add_list中的style_no和查询数据表数据的$production_order中的style_no字段
            foreach ($production_order as $pro_key => $pro_value) {
                if ($value == $pro_value->style_no) {
                    //将导入数据和$production_order字段style_no相同的数据累加
                    $order_num += $pro_value->order_num;
                    $shipment_num += $pro_value->shipment_num;
                }
            }
            //将值赋给$list
            $list[$key]['style_no'] = $value;
            $list[$key]['order_num'] = $order_num;
            $list[$key]['shipment_num'] = $shipment_num;
        }

        //// 存储数据
        if (empty($list)) {
            return 'Excel文件数据为空';
        }

        $insert = '';
        $update_style = '';
        $update_time = '';
        $update_order_num = '';
        $update_shipment_num = '';
        //找出$production_order中的style_no的值
        $production_style_no = array_column($production_order, 'style_no');
        //找出$style_no和$production_style_no中的不同值
        $diff = array_diff($style_no, $production_style_no);
        //添加数据
        $time = date('Y-m-d H:i:s', time());
        foreach ($list as $list_k => $list_v) {
            //判断如果$list中的style_no在$diff中
            if (in_array($list_v['style_no'], $diff)) {
                $insert .= "('{$list_v['style_no']}','{$list_v['order_num']}', '{$list_v['shipment_num']}','{$time}'),";
            } else {
                $update_order_num .= "WHEN '{$list_v['style_no']}' THEN '{$list_v['order_num']}' ";
                $update_shipment_num .= "WHEN '{$list_v['style_no']}' THEN '{$list_v['shipment_num']}' ";
                ///$update_time .= "WHEN '{$list_v['style_no']}' THEN '{$time}' ";
                $update_style .= "'{$list_v['style_no']}',";
            }

        }

        //去除多余的逗号
        $new_insert = substr($insert, 0, strlen($insert) - 1);
        $new_style = substr($update_style, 0, strlen($update_style) - 1);
        DB::beginTransaction();
        try {
            if (!empty($new_insert)) {
                $insert_sql = "insert into production_order(`style_no`,`order_num`,`shipment_num`,`time`) values {$new_insert}";
                $insert_res = Db::insert($insert_sql);

            }

            if (!empty($new_style)) {
                $update_sql = "update production_order
                                                    set `order_num` = Case style_no {$update_order_num} END,
                                                        `shipment_num` = Case style_no {$update_shipment_num} END,
                                                        `time` = '{$time}'
                                                    where `style_no` in ({$new_style})";
                $update = Db::update($update_sql);
            }
            DB::commit();
            return [
                'type' => 'success',
                'msg' => '导入成功'
            ];
        } catch (\Exception $e) {
            DB::rollBack();
            return [
                'type' => 'error',
                'msg' => $e->getMessage()
            ];
        }

    }

    //亚马逊补货计划导出
    public function plan_excel_export($params)
    {
        $sku_array = explode(',', $params['sku']);
        foreach ($sku_array as $key => $value) {
            $arr['sku'] = $value;
            $arr['express'] = '';
            $arr['ocean_shipping'] = '';
            $arr['air_transport'] = '';
            $list[] = $arr;
        }
        //表头
        $title = array(
            'sku' => 'SKU',
            'express' => '发货(快递)',
            'ocean_shipping' => '发货(海运)',
            'air_transport' => '发货(空运)'
        );
        $cellName = array('A', 'B', 'C', 'D');
        $file_name = '亚马逊补货计划导出';
        $this->excel_export_api($title, $list, $cellName, $file_name);
    }

    //补货预警导出
    public function warning_export($params)
    {
        $list = $this->getBuhuoWarn($params);


        $res = $this->amazon_warnExport($list);
        return $res;
    }

    /**
     * excel导出封装
     * $title array 表头
     * $list array 数据
     * $cellName array 占用的excel列（字母）
     * $file_name  string  文件名
     */
    public function excel_export_api($title, $list, $cellName, $file_name)
    {
        error_reporting(E_ALL);
        date_default_timezone_set('Europe/London');
        $objPHPExcel = new \PHPExcel();
        $PHPExcel_Style_Alignment = new\PHPExcel_Style_Alignment;
        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
//        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I');
        // 设置excel标题
        $index = 0;
        foreach ($title as $k => $v) {
            $objPHPExcel->getActiveSheet()->getStyle('A1:AU1')->getFont()->setBold(true);//第一行是否加粗
            $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(25);    //第一行行高
            $objPHPExcel->getActiveSheet()->setCellValue($cellName[$index] . "1", $v);
            $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(60);
            $objPHPExcel->getActiveSheet()->getDefaultColumnDimension()->setWidth(15);
            $index++;
        }
        //var_dump($list);die;
        foreach ($list as $k => $v) {
            $num = $k + 2;
            //字体大小
            $objPHPExcel->getActiveSheet()
                ->getStyle('A' . $num . ':' . 'AY' . $num)
                ->getFont()
                ->setSize(10);
            //设置水平居中
            $objPHPExcel->getActiveSheet()
                ->getStyle('A' . $num . ':' . 'AY' . $num)
                ->getAlignment()
                ->setHorizontal($PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //设置垂直居中
            $objPHPExcel->getActiveSheet()
                ->getStyle('A' . $num . ':' . 'AY' . $num)
                ->getAlignment()
                ->setVertical($PHPExcel_Style_Alignment::VERTICAL_CENTER);
            //自动换行
            $objPHPExcel->getActiveSheet()
                ->getStyle('A' . $num . ':' . 'AY' . $num)
                ->getAlignment()
                ->setWrapText(true);

            // 重置列索引起始位
            $i = 0;
            foreach ($title as $key => $value) {
                $objPHPExcel->setActiveSheetIndex(0)//Excel的第A列，uid是你查出数组的键值，下面以此类推
                ->setCellValue($cellName[$i] . $num, $v[$key]);
                $i++;
            }
        }
        $objPHPExcel->getActiveSheet()->setTitle('work');
        $objPHPExcel->setActiveSheetIndex(0);

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition:attachment;filename="' . $file_name . '.xls"');
        header('Cache-Control: max-age=1');
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter->save('php://output');
        exit();
    }

          /**
     * 亚马逊sku
     * @param Request $request
     */
    public function amazon_sku($params)
    {
        if (!isset($params['shop_id'])) {
            return $this->back('没有shop_id参数', '300');
        }
        if (!isset($params['sku'])) {
            return $this->back('没有sku参数', '300');
        }

        $skuList = explode(",", $params['sku']);

        $Shop = Shop::where('id', $params['shop_id'])->first();

        $shop['auth'] = json_decode($Shop['app_data'], true);
        $auth = $shop['auth'];

        require_once(app_path() . DIRECTORY_SEPARATOR . 'Libs' . DIRECTORY_SEPARATOR . 'MarketplaceWebServiceProducts' . DIRECTORY_SEPARATOR . 'Client.php');
        require_once(app_path() . DIRECTORY_SEPARATOR . 'Libs' . DIRECTORY_SEPARATOR . 'MarketplaceWebServiceProducts' . DIRECTORY_SEPARATOR . 'Model' . DIRECTORY_SEPARATOR . 'GetMatchingProductForIdRequest.php');
        require_once(app_path() . DIRECTORY_SEPARATOR . 'Libs' . DIRECTORY_SEPARATOR . 'MarketplaceWebServiceProducts' . DIRECTORY_SEPARATOR . 'Model' . DIRECTORY_SEPARATOR . 'SellerSKUListType.php');
        $serviceUrl = "https://mws.amazonservices.com/Products/2011-10-01";
        // Europe
        $serviceUrl_eu = "https://mws-eu.amazonservices.com/Products/2011-10-01";
        // Japan
        $serviceUrl_jp = "https://mws.amazonservices.jp/Products/2011-10-01";

        if ($auth['MARKETPLACE_ID'] == 'A1VC38T7YXB528') $serviceUrl = $serviceUrl_jp;
        if (in_array($auth['MARKETPLACE_ID'], array('A1F83G8C2ARO7P', 'A1PA6795UKMFR9', 'A1RKKUPIHCS9HS', 'A13V1IB3VIYZZH', 'APJ6JRA9NG5V4'))) $serviceUrl = $serviceUrl_eu;

        $config = array(
            'ServiceURL' => $serviceUrl,
            'ProxyHost' => null,
            'ProxyPort' => -1,
            'ProxyUsername' => null,
            'ProxyPassword' => null,
            'MaxErrorRetry' => 3,
        );

        $service = new \MarketplaceWebServiceProducts_Client(
            $auth['AWS_ACCESS_KEY_ID'],
            $auth['AWS_SECRET_ACCESS_KEY'],
            'MarketplaceWebServiceProducts PHP5 Library',
            '2',
            $config);

        /************************************************************************
         * Uncomment to try out Mock Service that simulates MarketplaceWebServiceProducts
         * responses without calling MarketplaceWebServiceProducts service.
         *
         * Responses are loaded from local XML files. You can tweak XML files to
         * experiment with various outputs during development
         *
         * XML files available under MarketplaceWebServiceProducts/Mock tree
         *
         ***********************************************************************/
        // $service = new MarketplaceWebServiceProducts_Mock();

        /************************************************************************
         * Setup request parameters and uncomment invoke to try out
         * sample for Get Matching Product For Id Action
         ***********************************************************************/
        // @TODO: set request. Action can be passed as MarketplaceWebServiceProducts_Model_GetMatchingProductForId
        $request = new \MarketplaceWebServiceProducts_Model_GetMatchingProductForIdRequest();
        $request->setSellerId($auth['MERCHANT_ID']);
        $request->setMarketplaceId($auth['MARKETPLACE_ID']);
        if (isset($auth['MWSAuthToken'])) $request->setMWSAuthToken($auth['MWSAuthToken']);
        $request->setIdType('SellerSKU');
        $idlist = new \MarketplaceWebServiceProducts_Model_SellerSKUListType();
        $idlist->setSellerSKU($skuList);
        $request->setIdList($idlist);

        try {
            $response = $service->GetMatchingProductForId($request);
            $dom = new \DOMDocument();
            $dom->loadXML($response->toXML());
            $dom->preserveWhiteSpace = false;
            $dom->formatOutput = true;
            $str = $dom->saveXML();
            $str = str_replace('ns2:', '', $str);
            $xml = simplexml_load_string($str);
            return json_decode(json_encode($xml), true);
        } catch (\MarketplaceWebServiceProducts_Exception $ex) {
            echo("Caught Exception: " . $ex->getMessage() . "\n");
            echo("Response Status Code: " . $ex->getStatusCode() . "\n");
            echo("Error Code: " . $ex->getErrorCode() . "\n");
            echo("Error Type: " . $ex->getErrorType() . "\n");
            echo("Request ID: " . $ex->getRequestId() . "\n");
            echo("XML: " . $ex->getXML() . "\n");
            echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
        }

    }
    public function get_lastday($year, $month)
    {
        if ($month == 2) {
            $lastday = $this->is_leapyear($year) ? 29 : 28;

        } elseif ($month == 4 || $month == 6 || $month == 9 || $month == 11) {
            $lastday = 30;

        } else {
            $lastday = 31;

        }
        return $lastday;
    }
    /**
     * @Desc: 补货计划列表导出
     * @param $params
     * @return mixed
     * @author: Liu Sinian
     * @Time: 2023/2/24 17:54
     */
    public function exportReplenishmentPlanList($params)
    {
        // 默认导出所有列表数据
        $replenishmentList = $this->replenishmentModel::query()
            ->leftJoin('amazon_create_goods as acg', 'acg.request_id', '=', 'amazon_buhuo_request.id');
        // 校验参数
        // 请求id
        if (isset($params['id']) && !empty($params['id'])){
            $replenishmentList->whereIn('amazon_buhuo_request.id', (array)$params['id']);
        }
        if (isset($params['plan_id']) && !empty($params['plan_id'])){
            $replenishmentList->where('amazon_buhuo_request.id', (array)$params['plan_id']);
        }
        // 店铺
        if (isset($params['store_id']) && !empty($params['store_id'])){
            $replenishmentList->where('amazon_buhuo_request.shop_id', $params['store_id']);
        }
        // 申请人
        if (isset($params['request_user_id']) && !empty($params['request_user_id'])){
            $replenishmentList->where('amazon_buhuo_request.request_userid', $params['request_user_id']);
        }
        // 申请单状态
        if (isset($params['status_id']) && !empty($params['status_id'])){
            $replenishmentList->whereIn('amazon_buhuo_request.request_status', $params['status_id']);
        }
        // 仓库
        if (isset($params['warehouse']) && !empty($params['warehouse'])){
            $replenishmentList->where('amazon_buhuo_request.warehouse', $params['warehouse']);
        }
        // 请求时间
        if (isset($params['request_time']) && !empty($params['request_time'])){
            $replenishmentList->whereBetween('amazon_buhuo_request.request_time', $params['request_time']);
        }
        // 运输方式
        if (isset($params['shipping_type']) && !empty($params['shipping_type'])){
            if ($params['shipping_type'] == 1){
                $replenishmentList->where('amazon_buhuo_request.courier_date', '<>', '1970-01-01');
            }elseif ($params['shipping_type'] == 2){
                $replenishmentList->where('amazon_buhuo_request.shipping_date', '<>', '1970-01-01');
            }elseif ($params['shipping_type'] == 3){
                $replenishmentList->where('amazon_buhuo_request.air_date', '<>', '1970-01-01');
            }
        }
        // 库存sku
        if (isset($params['custom_sku']) && !empty($params['custom_sku'])){
            $detail = $this->replenishmentDetailModel::query()
                ->where('custom_sku', 'like', $params['custom_sku'])
                ->select('request_id')
                ->get()
                ->toArray();
            $requestIds = array_column($detail, 'request_id');
            $replenishmentList->whereIn('amazon_buhuo_request.id', $requestIds);
        }
        // 获取补货申请单
        $replenishmentList = $replenishmentList
            ->select('amazon_buhuo_request.*', 'acg.request_id', 'acg.DestinationFulfillmentCenterId', 'acg.box_ids', 'acg.file_name', 'acg.serial_no',
                'acg.tracking_no')
            ->get();

        $list = [];
        /**
         * 优化方案：
         * 查询所有创货单表数据
         * 查询需要导出的补货单数据
         * 循环创货单数据
         *      循环补货单数据
         *          判断补货单id是否相等
         *              相等则增加导出数据
         */
        $goodsList = [];
        $boxMdl = db::table('amazon_box_data')
            ->get();
        $boxList = [];
        foreach ($boxMdl as $box){
            if (isset($boxList[$box->request_id])){
                $boxList[$box->request_id]['box_num'] += $box->box_num;
                $boxList[$box->request_id]['box_no'][] = $box->box_id;
            }else{
                $boxList[$box->request_id] = [
                    'box_num' => $box->box_num,
                    'box_no' => [$box->box_id]
                ];
            }
        }
        $boxItemMdl = db::table('amazon_box_data_detail')
            ->get();
        $boxItemList = [];
        foreach ($boxItemMdl as $box){
            $key = $box->request_id.'-'.$box->box_no;
            if (isset($boxItemList[$key])){
                $boxItemList[$key] += $box->actual_num;
            }else{
                $boxItemList[$key] = $box->actual_num;
            }
        }
        foreach ($replenishmentList as $item){
            // 判断物流方式
//            $logisticsMode = $this->_judgeLogixticsMode($item);
            // 商品信息
            $replenishmentDetail = $this->replenishmentDetailModel::query()->where('request_id', $item->id)->get()->toArray();
            $productNumArr = array_column($replenishmentDetail, 'box_data_detail');
//            $productNum = 0;
//            foreach ($productNumArr as $v){
//                $productNum += array_sum(json_decode($v, true));
//            }
            $customSku = $this->customSkuModel::query()->whereIn('id', array_column($replenishmentDetail, 'custom_sku_id'))->get()->toArray();
            $product = implode(', ', array_column($customSku, 'name'));
//            $customSku = DB::table('product_detail')->whereIn('custom_sku_id', array_column($replenishmentDetail, 'custom_sku_id'))->get()->toArray();
//            $product = implode(', ', array_column($customSku, 'title'));
            // 店铺信息
            $shop = $this->GetShop($item->shop_id);
            // 查询箱号
            $boxData = $this->boxDataModel::query()
                ->where('request_id', $item->id);
            // 创货件数据boxids不为空，则区分创货件的箱子数据
            $boxIds = [];
            $actual_num = 0;
            if (!empty($item->box_ids)){
                $boxIds = explode(',', $item->box_ids);
                $boxData->whereIn('box_id', $boxIds);

                foreach ($boxIds as $bId){
                    $key = $item->id . '-'. $bId;
                    if (isset($boxItemList[$key])){
                        $actual_num += $boxItemList[$key];
                    }
                }
            }
            $boxData = $boxData->get()->toArray();
            $boxNum = count($boxData);
            $productNum = array_sum(array_column($boxData, 'box_num'));
            if (isset($goodsList[$item->id])){
                $goodsList[$item->id]['box_num'] += $productNum;
                $goodsList[$item->id]['box_no'][] = $boxIds;
            }else{
                $goodsList[$item->id] = [
                    'box_num' => $productNum,
                    'box_no' => $boxIds
                ];
            }
            $heavy = array_sum(array_column($boxData, 'heavy'));
            $freight = bcmul($item->logistics_price * $item->calculate_heavy, 2); // 运费
            $volume = 0; // 立方数
            foreach ($boxData as $box){
                $volume += ($box['Long'] * $box['wide'] * $box['high'])/1000000;
            }
            $national = self::NATIONAL_IDENTITY[$shop['region']] ?? ''; // 国家标识
            $warehouse = $item->DestinationFulfillmentCenterId ?? ''; // 目的仓库
            $shoppingAddress = $item->shopping_address ?? ''; // 目的地址
            $boxIds = implode(',', array_column($boxData, 'box_id'));
            $userMdl = $this->GetUsers($item->request_userid);
            $requestUserName = $userMdl['account'] ?? '';
            $list[] = [
                'id' => $item->id, // 任务ID
                'shop_name' => $shop['shop_name'] ?? '', // 店铺名称
                'delivery_date' => $item->delivery_date ?? '', // 发货日期
                'arrival_date' => $logisticsMode['date'] ?? '', // 到达日期
                'carrier' => '', // 承运商
                'purpose_warehouse' => $national . '-' . $warehouse, // 目的仓库 需要凭借国家标识
                'product' => $product ?? '', // 商品
                'product_num' => $productNum ?? 0, // 数量
                'box_num' => $boxNum ?? 0, // 箱数
                'heavy' => $heavy ?? 0, // 重量
                'volume' => round($volume ?? 0.000, 3), // 立方数
                'logistics_mode' => $item->transportation_mode_name ?? '', // 物流方式
                'freight' => round($freight ?? 0.00, 2), // 运费
                'logistics_order_no' => $item->logistics_order_no ?? '', // 运单号
                'logistics_price' => round($item->logistics_price ?? 0.00, 2) , // 单件运费
                'fba' => "货件名称：{$item->file_name} 编号：{$item->serial_no} 货件追踪编号：{$item->tracking_no}",
                'box_ids' => $boxIds, // 箱号
                'request_user_name' => $requestUserName,
                'actual_num' => $actual_num,
                'null1' => '',
                'null2' => '',
                'null3' => '',
            ];
        }
        $errorMsg = '';
        foreach ($goodsList as $k => $v){
            $box = $boxList[$k] ?? [];
            if (empty($box)){
                $errorMsg .= '补货计划ID：'.$k.'补货装箱详情为空！';
                continue;
            }
            if ($box['box_num'] != $v['box_num']){
                $errorMsg .= '补货计划ID：'.$k.'装箱数量与创货件绑定装箱数量不一致！补货装箱总数量为：'.$box['box_num'].'，箱号为：'.implode(',', $box['box_no']).'；创货件绑定装箱总数量为：'.$v['box_num'].'，箱号为：'.implode(',', $v['box_no']).'；';
                continue;
            }
        }
//        if (!empty($errorMsg)){
//            throw new \Exception($errorMsg);
//        }

        // excel文件表头
        $excelName = '补货计划导出'.time();
        // 表头
        $excelTitle = [
            'id' => '任务ID',
            'shop_name' => '店铺名称',
            'delivery_date' => '发货日期',
            'arrival_date' => '到达日期',
            'null1' => '',
            'carrier' => '承运商',
            'logistics_mode' => '物流方式',
            'purpose_warehouse' => '目的仓库',
            'product' => '商品',
            'product_num' => '数量',
            'actual_num' => '实际装箱数量',
            'box_num' => '箱数',
            'heavy' => '重量',
            'volume' => '立方数',
            'freight' => '运费',
            'null2' => '',
            'logistics_order_no' => '运单号',
            'null3' => '',
            'logistics_price' => '单件运费',
            'fba' => 'FBA#',
            'box_ids' => '箱号',
            'request_user_name' => '补货申请人',
        ];
        // 组织导出列表数据
        $excelData = [
            'data' => $list,
            'title_list' => $excelTitle,
            'title' => $excelName,
            'type' => '补货计划导出',
            'user_id' => $params['export_user_id']
        ];

        return ['data' => $excelData, 'error_msg' => $errorMsg];
    }

    /**
     * @Desc:判断物流方式
     * @param $data
     * @return array|string[]
     * @author: Liu Sinian
     * @Time: 2023/2/24 17:58
     */
    private function _judgeLogixticsMode($data)
    {
        $result = [
            'name' => '',
            'date' => '',
        ];
        if ($data->courier_date != '1970-01-01'){
            $result = [
                'name' => '快递',
                'date' => $data->courier_date
            ];
        }
        if ($data->shipping_date != '1970-01-01'){
            $result = [
                'name' => '海运',
                'date' => $data->shipping_date
            ];
        }
        if ($data->air_date != '1970-01-01'){
            $result = [
                'name' => '空运',
                'date' => $data->air_date
            ];
        }

        return $result;
    }

    /**
     * @Desc:查询n天内店铺内款式补货数据
     * @param $shopId
     * @param $customSkuId
     * @param $requestId
     * @param $day
     * @param $page
     * @param $limit
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/2/27 16:47
     */
    public function getLastMonthStyleReplenishList($shopId, $customSkuId, $requestId, $day, $page, $limit)
    {
        try {
            // 验证是否传入请求id
            if (empty($requestId)){
                throw new \Exception('没有给定申请单标识！');
            }
            // 如果没有传具体库存sku，则查询所有款式的数据
            if (empty($customSkuId)){
                // 查询该补货请求下所有款式
                $replenishmentDetail = $this->replenishmentDetailModel::query()
                    ->where('request_id', $requestId)
                    ->get()
                    ->toArray();
                $customSkuId = array_column($replenishmentDetail, 'custom_sku_id');
            }

            // 查询款式近30天数据,且不包含当前请求下的详情数据
            $replenishmentDetail = $this->replenishmentDetailModel::query()
                ->where('request_id', '<>', $requestId)
                ->where('amazon_buhuo_detail.shop_id', $shopId)
                ->whereIn('amazon_buhuo_detail.custom_sku_id', (array)$customSkuId)
                ->whereBetween('amazon_buhuo_detail.create_time', [strtotime(Carbon::today()->subDay($day)), strtotime(Carbon::today())])
                ->join('amazon_buhuo_request', 'amazon_buhuo_detail.request_id', '=', 'amazon_buhuo_request.id')
                ->select('amazon_buhuo_detail.*', 'amazon_buhuo_request.*')
            ; // 转换成时间戳才能匹配到数据

            $count = $replenishmentDetail->count();
            $replenishmentDetail = $replenishmentDetail->offset($page)->limit($limit)->get();

            $list = [];
            foreach ($replenishmentDetail->toArray() as $key => &$item) {
                $shop = $this->GetShop($item['shop_id']) ?? [];
                $item['shop_name'] = $shop['shop_name'] ?? '';
                $item['operating_personnel'] = $item['update_user'] ?? ''; // 运营人员
                $item['logixtics_mode'] = $item['transportation_mode_name'] ?? ''; // 物流方式
                $item['replenishment_num'] = $item['request_num'] ?? 0; // 补货数量
                $item['transportation_type'] = self::TRANSPORTATION_TYPE[$item['transportation_type']] ?? '';
                $list[] = $item;
            }
            $result = [
                'count' => $count,
                'list' => $list
            ];

            return ['code' => 200, 'msg' => '获取成功！', 'data' => $result];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @Desc: 保存运输方式
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/4/3 15:08
     */
    public function saveTransportationMode($params)
    {
        try {
            // 校验数据
            $params = $this->_filterTransportationModeParams($params);
            // 保存数据
            $id = $params['id'] ?? 0;
            if ($id){
                // 更新
                $result = $this->transportationModeModel::query()
                    ->where('id', $id)
                    ->update($params);
            }else{
                // 新增
                $id = $this->transportationModeModel::query()
                    ->insertGetId($params);
            }

            if ($id){
                return ['code' => 200, 'msg' => '保存成功！', 'data' => 'id => '. $id];
            }else{
                throw new \Exception('保存出错！');
            }
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '保存失败！原因：'. $e->getMessage()];
        }
    }

    private function _filterTransportationModeParams($params)
    {
        // 判断运输方式名称
        if (isset($params['name']) && !empty($params['name'])){
            $modeMdl = $this->transportationModeModel::query()
                ->where('name', $params['name'])
                ->first();
            // 判断是否更新
            if (isset($params['id']) && !empty($params['id'])){
                $mode = $this->transportationModeModel::query()
                    ->where('id', $params['id'])
                    ->first();
                if (empty($mode)){
                    throw new \Exception('该物流方式不存在！');
                }
                if (!empty($modeMdl->name) && $modeMdl->name != $mode->name){
                    throw new \Exception('运输方式名称已存在！');
                }
                $params['updated_at'] = date('Y-m-d H:i:s');
            }else{
                if (!empty($modeMdl)){
                    throw new \Exception('运输方式名称已存在！');
                }
                $params['created_at'] = date('Y-m-d H:i:s');
            }
        }else{
            throw new \Exception('物流方式名称未给定！');
        }

        if (isset($params['price']) && $params['price'] < 0){
            throw new \Exception('价格不正确！');
        }

        if (!isset($params['type']) || empty(self::TRANSPORTATION_TYPE[$params['type']] ?? '')){
            throw new \Exception('运输类型未给定或非预设值！');
        }

        if (isset($params['expected_duration']) && $params['expected_duration'] < 0){
            throw new \Exception('预计运输时长不正确！');
        }

        return $this->allowField($params, 'transportation_mode');
    }

    /**
     * @Desc: 获取运输方式列表
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/4/3 15:30
     */
    public function getTransportationModeList($params)
    {
        $modeModel = $this->transportationModeModel::query();

        if (isset($params['name']) && !empty($params['name'])){
            $modeModel->where('name', 'like', '%'.$params['name'].'%');
        }

        $count = $modeModel->count();
        $limit = $params['limit'] ?? 30;
        $page = $params['page'] ?? 1;
        $pageNum = $limit*($page-1);

        $modeModel = $modeModel->limit($limit)
            ->offset($pageNum)
            ->orderBy('price', 'ASC')
            ->orderBy('updated_at', 'DESC')
            ->get();
        foreach ($modeModel as $item){
            $item->type_name = self::TRANSPORTATION_TYPE[$item->type] ?? '';
            $item->expected_duration = $item->expected_duration.'天';
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $modeModel]];
    }

    /**
     * @Desc: 删除运输方式（可批量）
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/4/3 15:31
     */
    public function deleteTransportationMode($params)
    {
        if (!isset($params['id']) || empty($params['id'])){
            return ['code' => 500, 'msg' => '未给定标识！'];
        }

        $result = $this->transportationModeModel::query()
            ->whereIn('id', $params['id'])
            ->delete();

        return ['code' => 200, 'msg' => '删除成功！删除了'.$result.'条数据！'];
    }


    public function updateBuhuoRequestNum($params)
    {
        try {
            $buhuoRequestMdl = $this->amazonBuhuoReqeustModel::query()
                ->leftJoin('amazon_buhuo_detail as a', 'a.request_id', '=', 'amazon_buhuo_request.id')
                ->whereNull('a.transportation_type')
//                ->whereIn('amazon_buhuo_request.id', [10005185,10005187])
                ->get(['amazon_buhuo_request.*', 'a.id as detail_id', 'a.request_id', 'a.courier_num', 'a.shipping_num', 'a.air_num']);
            $updateId = [];
            $notUpdateId = [];
            $notUpdateDetailId = [];
            DB::beginTransaction();
            foreach ($buhuoRequestMdl as $item){
                $data = [
                    'id' => $item->id,
                    'detail_id' => $item->detail_id
                ];
                if ($item->courier_date != '1970-01-01'){
                    $data['transportation_mode_name'] = '快递';
                    $data['transportation_type'] = 2;
                    $data['transportation_date'] = $item->courier_date;
                }
                elseif ($item->shipping_date != '1970-01-01'){
                    $data['transportation_mode_name'] = '海运';
                    $data['transportation_type'] = 1;
                    $data['transportation_date'] = $item->shipping_date;
                }
                elseif ($item->air_date != '1970-01-01'){
                    $data['transportation_mode_name'] = '空运';
                    $data['transportation_type'] = 3;
                    $data['transportation_date'] = $item->air_date;
                }
                else{
                    $notUpdateId[] = $data['id'];
                    $notUpdateDetailId[] = $data['detail_id'];
                    continue;
                }
                $data['request_num'] = $item->courier_num + $item->shipping_num + $item->air_num;
                if (!in_array($data['id'], $updateId)){
                    $update = $this->amazonBuhuoReqeustModel::query()
                        ->where('id', $data['id'])
                        ->update(['transportation_mode_name' => $data['transportation_mode_name'], 'transportation_date' => $data['transportation_date']]);
                    if ($update){
                        $updateId[] = $data['id'];
                    }else{
                        $notUpdateId[] = $data['id'];
                        $notUpdateDetailId[] = $data['detail_id'];
                        continue;
                    }
                }
                $update = $this->amazonBuhuoDetailModel::query()
                    ->where('id', $data['detail_id'])
                    ->update(['transportation_mode_name' => $data['transportation_mode_name'], 'transportation_type' => $data['transportation_type'], 'request_num' => $data['request_num']]);
                if (!$update) {
                    $notUpdateDetailId[] = $data['detail_id'];
                }
            }

            DB::commit();

            return ['code' => 200, 'msg' => '更新完毕! 未更新请求id为：'.implode(',', array_unique($notUpdateId)).'，未更新详情id为'.implode(',', array_unique($notUpdateDetailId))];
        }catch (\Exception $e){
            DB::rollback();
            return ['code' => 500, 'msg' => '更新出错！错误原因：'.$e->getMessage()];
        }
    }

    public function batchUpdateSkulist($params)
    {
        try {
            if (!isset($params['skus']) || empty($params['skus'])){
                throw new \Exception('未给定sku');
            }
            $result = [];
            foreach ($params['skus'] as $sku){
                $result = $this->updateSkulist(['sku' => $sku]);
            }

            return ['code' => 200, 'msg' => '批量更新成功！由于存在延迟，请稍后查看~', 'data' => $result];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '批量更新失败！错误原因：'.$e->getMessage()];
        }
    }

    public function exportBuhuoRequestBoxData($params)
    {
        try {
            $list = $this->select_buhuoDoc($params)['data'] ?? [];
            if (empty($list)){
                throw new \Exception('请选择需要导出的数据！');
            }

            $requestIds = array_column($list, 'id');
            $createGoodMdl = db::table('amazon_create_goods')->whereIn('request_id', $requestIds)->get();
            if ($createGoodMdl->isEmpty()){
                throw new \Exception('无创货件数据！');
            }
            $boxData = db::table('amazon_box_data')->whereIn('request_id', $requestIds)->get();
            if ($boxData->isEmpty()){
                throw new \Exception('无装箱数据！');
            }
            $list = [];
            foreach ($createGoodMdl as $item){
                $boxNos = explode(',', $item->box_ids);
                $boxCount = count($boxNos);
                foreach ($boxData as $box){
                    if ($item->request_id == $box->request_id){
                        if (in_array($box->box_id, $boxNos)){
                            $list[] = [
                                'request_id' => $item->request_id,
                                'serial_no' => $item->serial_no,
                                'box_count' => $boxCount,
                                'box_no' => $box->box_id,
                                'long' => $box->Long,
                                'wide' => $box->wide,
                                'high' => $box->high,
                                'heavy' => $box->heavy,
                                'box_num' => $box->box_num,
                            ];
                        }
                    }
                }
            }
            // excel文件表头
            $excelName = '补货计划装箱导出'.time();
            // 表头
            $excelTitle = [
                'request_id' => '补货计划ID',
                'serial_no' => '货件编号',
                'box_count' => '箱数',
                'box_no' => '箱号',
                'long' => '长',
                'wide' => '宽',
                'high' => '高',
                'heavy' => '重量',
                'box_num' => '数量',
            ];
            // 组织导出列表数据
            $excelData = [
                'data' => $list,
                'title_list' => $excelTitle,
                'title' => $excelName,
                'type' => '补货计划装箱导出',
                'user_id' => $params['export_user_id']
            ];

            return ['data' => $excelData, 'error_msg' => ''];;
        }catch (\Exception $e){
            throw new \Exception('获取错误！错误原因：'.$e->getMessage().'；位置：'.$e->getLine());
        }
    }

    public function getCustomSkuLockDetail($params)
    {
        $customSkuModel = db::table('self_custom_sku')->where('id', $params['custom_sku_id'])->first();
        $boxDetail = [];
        if ($customSkuModel){
            $searchCustonSkuId = $params['custom_sku_id'];
            if ($customSkuModel->type == 2){
                $groupCustomSkuModel = db::table('self_group_custom_sku')->where('custom_sku_id', $searchCustonSkuId)->get();
                $groupCustomSkuModel = json_decode(json_encode($groupCustomSkuModel), true);
                $searchCustonSkuId = array_column($groupCustomSkuModel, 'group_custom_sku_id');
            }
            $boxDetail = $this->GetLocationCustomSkuLockNum($searchCustonSkuId, $params['location_id'] ?? 0,$params['warehouse_id'] ?? 0, $params['platform_id'] ?? 0);
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => $boxDetail];
    }

    public function checkFasinCodeStrategy($params)
    {
        try{
            if (!isset($params['sku_id']) || empty($params['sku_id'])){
                throw new \Exception('未给定sku标识！');
            }
            if (!isset($params['shop_id']) || empty($params['shop_id'])){
                throw new \Exception('未给定店铺标识！');
            }
            $skuMdl = db::table('self_sku')->whereIn('id', $params['sku_id'])->get();
            $sku = [];
            if ($skuMdl->isNotEmpty()){
                $sku = $skuMdl->toArrayList();
            }
            $fasinList = array_filter(array_unique(array_column($sku, 'fasin')));
            $fasinCode = db::table('amazon_fasin_bind')->whereIn('fasin', $fasinList)->where('shop_id', $params['shop_id'])->where('strategy', 'like', '%F%')->get();

            $list = [];
            $msg = '';
            $pop = false;
            foreach ($fasinCode as $v){
                foreach ($skuMdl as $_v){
                    if ($v->fasin == $_v->fasin){
                        $pop = true;
                        $list[] = [
                            'sku_id' => $_v->id,
                            'sku' => $_v->sku,
                            'fasin_code' => $v->fasin_code,
                            'fasin' => $v->fasin,
                            'strategy' => $v->strategy
                        ];
                        $msg .= "<span style='color: red;'>".$_v->sku."</span>；";
                    }
                }
            }
            $msg .= '以上sku指导策略为亏损，请谨慎下单！';

            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['pop' => $pop, 'list' => $list, 'msg' => $msg]];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }

    }

    public function saveReplenishmentPackingDetail($params)
    {
        try {
            // 校验保存数据
            $params = $this->_checkSavePackData($params);
            db::beginTransaction();
            // 判断新增/更新
            if (isset($params['box_no']) && !empty($params['box_no'])){
                // 更新
                $boxNo = $params['box_no'];
                db::table('amazon_box_data_detail')->where('request_id', $params['request_id'])->where('box_no', $boxNo)->delete();
                $updatedAt = date('Y-m-d H:i:s');
            }else{
//                // 自动接受任务
//                $boxDetailMdl = db::table('amazon_box_data_detail')
//                    ->where('request_id', $params['request_id'])
//                    ->first();
//                if (empty($boxDetailMdl)){
//                    // 查询任务节点情况
//                    $request_id_json = substr(substr(json_encode(array("request_id" => "{$params['request_id']}")), 1), 0, -1);
//                    $taskMdl = Db::table('tasks')->where('ext', 'like', '%'.$request_id_json.'%')
//                        ->where('state', '<>', 2)
//                        ->where('is_deleted', 0)
//                       ->first();
//                    if (empty($taskMdl)){
//                        throw new \Exception('未查询到补货计划任务！');
//                    }
//                    $taskNodeMdl = db::table('tasks_node')
//                        ->where('task_id', $taskMdl->Id)
//                        ->where('name', '备货装箱')
//                        ->update(['state' => 2, 'time_state' => date('Y-m-d H:i:s')]);
//                }
                // 新增
                $endBox = db::table('amazon_box_data_detail')->where('request_id', $params['request_id'])->orderBy('box_no', 'DESC')->first();

                if (empty($endBox)){
                    $boxNo = 1;
                }else{
                    $boxNo = $endBox->box_no + 1;
                }
            }
            foreach ($params['items'] as $item){
                $save = [
                    'request_id' => $params['request_id'],
                    'box_no' => $boxNo,
                    'custom_sku_id' => $item['custom_sku_id'],
                    'custom_sku' => $item['custom_sku'],
                    'spu_id' => $item['spu_id'],
                    'spu' => $item['spu'] ?? '',
                    'num' => $item['num'],
                    'actual_num' => $item['actual_num'],
                    'user_id' => $params['user_id'],
                    'long' => $params['box_long'],
                    'wide' => $params['box_wide'],
                    'high' => $params['box_high'],
                    'heavy' => $params['box_heavy'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => $updatedAt ?? ''
                ];

                $saveId = db::table('amazon_box_data_detail')->insertGetId($save);
                if (empty($saveId)){
                    throw new \Exception('数据保存失败！错误数据：'.json_encode($item));
                }
            }
            db::commit();
            return ['code' => 200, 'msg' => '保存成功！'];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '保存失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    private function _checkSavePackData($params)
    {
        if (!isset($params['box_code']) || empty($params['box_code'])){
            throw new \Exception('未给定箱码！');
        }else{
            $boxMdl = db::table('goods_transfers_box')->where('box_code', $params['box_code'])->first();
            if (empty($boxMdl)){
                throw new \Exception('未查询到箱码数据！');
            }
            $params['request_id'] = $boxMdl->order_no;
            $requestMdl = db::table('amazon_buhuo_request')->where('id', $params['request_id'])->first();
            if (empty($requestMdl)){
                throw new \Exception('未查询到补货计划数据！');
            }
        }
        if (!isset($params['user_id']) || empty($params['user_id'])){
            throw new \Exception('未给定操作人标识！');
        }
        if (!isset($params['box_long']) || $params['box_long'] <= 0){
            throw new \Exception('装箱长度属性数值有误！');
        }
        if (!isset($params['box_wide']) || $params['box_wide'] <= 0){
            throw new \Exception('装箱宽度属性数值有误！');
        }
        if (!isset($params['box_high']) || $params['box_high'] <= 0){
            throw new \Exception('装箱高度属性数值有误！');
        }
        if (!isset($params['box_heavy']) || $params['box_heavy'] <= 0){
            throw new \Exception('装箱重量属性数值有误！');
        }
        if (!isset($params['items']) || empty($params['items'])){
            throw new \Exception('装箱详情为空！');
        }else{
            $error = '';
            $customSkuNum = [];
            $groupSkuMdl = db::table('self_group_custom_sku')->get();
            $customSkuMdl = db::table('self_custom_sku')->get();
            $customSkuType = [];
            foreach ($customSkuMdl as $v){
                $customSkuType[$v->id] = $v->type;
            }
            foreach ($params['items'] as $k => $v){
                if (!isset($v['custom_sku']) || empty($v['custom_sku'])){
                    $error .= '第'.($k+1).'行未给定库存sku！';
                    continue;
                }
                $customSku = isset($v['old_custom_sku'])&&!empty($v['old_custom_sku']) ? $v['old_custom_sku'] : $v['custom_sku'];
                if (!isset($v['custom_sku_id']) || empty($v['custom_sku_id'])){
                    $error .= '库存sku：'.$customSku.'未给定库存sku标识！';
                    continue;
                }
                if (!isset($v['spu_id']) || empty($v['spu_id'])){
                    $error .= '库存sku：'.$customSku.'未给定spu标识！';
                    continue;
                }
                if (!isset($v['num']) || $v['num'] <= 0){
                    $error .= '库存sku：'.$customSku.'数量不合法！';
                    continue;
                }
                if (array_key_exists($v['custom_sku_id'], $customSkuNum)){
                    $customSkuNum[$v['custom_sku_id']] += $v['num'];
                }else{
                    $customSkuNum[$v['custom_sku_id']] = $v['num'];
                }
                // 计算实际数量
                $type = $customSkuType[$v['custom_sku_id']] ?? 0;
                if (empty($type)){
                    $error .= '库存sku：'.$customSku.'未查询到类型！';
                    continue;
                }
                $n = 1; // 单品倍数为1，组合根据实际数量计算倍数
                if ($type == 2){
                    $i = 0;
                    foreach ($groupSkuMdl as $gsku){
                        if ($gsku->custom_sku_id == $v['custom_sku_id']){
                            $i += 1;
                        }
                    }
                    $n = $i;
                }
                $actualNum = $v['num'] * $n;
                $params['items'][$k]['actual_num'] = $actualNum;
            }
            $boxDataMdl = db::table('amazon_box_data_detail')
                ->where('request_id', $params['request_id']);
            if (isset($params['box_no']) && !empty($params['box_no'])){
                $boxDataMdl = $boxDataMdl->where('box_no', '<>', $params['box_no']);
            }
            $boxDataMdl = $boxDataMdl->get();
            foreach ($boxDataMdl as $v){
                if (array_key_exists($v->custom_sku_id, $customSkuNum)){
                    $customSkuNum[$v->custom_sku_id] += $v->num;
                }else{
                    $customSkuNum[$v->custom_sku_id] = $v->num;
                }
            }
            $requestDetailMdl = db::table('amazon_buhuo_detail')
                ->where('request_id', $params['request_id'])
                ->get();
            foreach ($requestDetailMdl as $item){
                if (array_key_exists($item->custom_sku_id, $customSkuNum)){
                    $totalNum = $customSkuNum[$item->custom_sku_id];
                    if ($totalNum > $item->request_num){
                        $error .= '库存sku：'.$item->custom_sku.'装箱数量不可超过计划补货数量，补货请求数量为：'.$item->request_num.'，装箱数量为：'.$totalNum;
                        continue;
                    }
                }
            }
            if (!empty($error)){
                throw new \Exception($error);
            }
        }

        return $params;
    }

    public function getReplenishmentPackingDetailList($params)
    {
        $mdl = db::table('amazon_box_data_detail as a')
            ->leftJoin('self_custom_sku as b', 'a.custom_sku_id', '=', 'b.id');

        if (isset($params['box_code']) && !empty($params['box_code'])){
            $boxMdl = db::table('goods_transfers_box')->where('box_code', $params['box_code'])->first();
            if(empty($boxMdl)){
                return ['code' => 500, 'msg' => '获取失败！未查询到中转箱信息！'];
            }
            $mdl = $mdl->where('a.request_id', $boxMdl->order_no);
        }

        $mdl = $mdl->orderBy('box_no', 'ASC')
            ->orderBy('created_at', 'DESC')
            ->get();
        $groupSkuMdl = db::table('self_group_custom_sku')->get();
        $list = [];
        foreach ($mdl as $v){
            $no = $v->request_id .'-'. $v->box_no;
            $userName = $this->GetUsers($v->user_id)['account'] ?? '';
//            foreach ($customSkuMdl as $sku){
//                if ($v->custom_sku_id == $sku->id){
//                    $v->type = $sku->type;
//                }
//            }

//            $n = 1; // 单品倍数为1，组合根据实际数量计算倍数
//            if ($v->type == 2){
//                $i = 0;
//                foreach ($groupSkuMdl as $gsku){
//                    if ($gsku->custom_sku_id == $v->custom_sku_id){
//                        $i += 1;
//                    }
//                }
//                $n = $i;
//            }
//            $actualNum = $v->num * $n;
            if (array_key_exists($no, $list)){
                $list[$no]['total_num'] += $v->num;
                $list[$no]['total_actual_num'] += $v->actual_num;
            }else{
                $list[$no] = [
                    'request_id' => $v->request_id,
                    'long' => $v->long,
                    'wide' => $v->wide,
                    'high' => $v->high,
                    'box_no' => $v->box_no,
                    'heavy' => $v->heavy,
                    'total_num' => $v->num,
                    'user_name' => $userName,
                    'total_actual_num' => $v->actual_num
                ];
            }
            $list[$no]['detail'][] = [
                'custom_sku_id' => $v->custom_sku_id,
                'custom_sku' => $v->custom_sku,
                'spu_id' => $v->spu,
                'spu' => $v->spu,
                'num' => $v->num,
                'actual_num' => $v->actual_num,
                'name' => $v->name,
                'img' => $v->img,
                'color' => $v->color,
                'color_name' => $v->color_name,
                'size' => $v->size
            ];
        }
        $list = array_values($list);

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => count($list), 'list' => $list]];
    }

    public function saveAmazonBoxData($params)
    {
        try {
            // 校验装箱码
            if (!isset($params['box_code']) || empty($params['box_code'])){
                throw new \Exception('未给定中转箱码！');
            }
            $transfersBoxMdl = db::table('goods_transfers_box')->where('box_code', $params['box_code'])->first();
            if (empty($transfersBoxMdl)){
                throw new \Exception('未查询到该中转箱数据！');
            }
            // 获取补货计划
            $params['request_id'] = $transfersBoxMdl->order_no;
            $requestMdl = db::table('amazon_buhuo_request')->where('id', $params['request_id'])->first();
            if (empty($requestMdl)){
                throw new \Exception('未查询到补货请求数据！');
            }
            if ($requestMdl->request_status < 4){
                throw new \Exception('请求计划当前状态不可装箱！');
            }
            // 查询任务节点情况
            $request_id_json = substr(substr(json_encode(array("request_id" => "{$params['request_id']}")), 1), 0, -1);
            $task_data = Db::table('tasks')->where('ext', 'like', "%{$request_id_json}%")->where('is_deleted', 0)->where('state','!=',2)->select('Id', 'name', 'user_fz','class_id')->get()->toArray();
            if ($task_data) {
                $task_id = $task_data[0]->Id;
            } else {
                throw new \Exception('该计划未发布任务，tasks表');
            }
            $task_son = Db::table('tasks_son')->select('Id', 'user_id','state','day_yj')->where(['task_id' => $task_id])->get()->toArray();
            if($task_data[0]->class_id==3){
                if($task_son[0]->state==1)
                    throw new \Exception('请先接受装箱任务！');
                $taskArr['Id'] = $task_son[0]->Id;
                $task2_id = $task_son[0]->Id;
            }elseif($task_data[0]->class_id==4){
                if($task_son[0]->state==1)
                    throw new \Exception('请先接受装箱任务！');
                $taskArr['Id'] = $task_son[0]->Id;
            }
            $taskArr['state'] = 3;
            $taskArr['feedback_type'] = 1;
            $call_task = new \App\Libs\wrapper\Task();

            db::beginTransaction();    //开启事务
            if (!isset($params['list']) || empty($params['list'])){
                throw new \Exception('未给定装箱数据！');
            }
            $boxAllTotal = 0; // 统计装箱总件数(组合按套计算)
            $boxActualNum = 0; // 统计装箱实际总件数
            $boxDataDetail = []; // 保存装箱详情数据
            $boxNos = [];
            foreach ($params['list'] as $v){
                // 保存装箱数据
                $boxDataId = db::table('amazon_box_data')->insertGetId([
                    'request_id' => $v['request_id'],
                    'box_id' => $v['box_no'],
                    'heavy' => $v['heavy'],
                    'Long' => $v['long'],
                    'wide' => $v['wide'],
                    'high' => $v['high'],
                    'box_num' => $v['total_actual_num'],
                    'creat_time' => date('Y-m-d H:i:s'),
                ]);
                // 组织装箱详情数据
                foreach ($v['detail'] as $item){
                    if (array_key_exists($item['custom_sku_id'], $boxDataDetail)){
                        if (isset($boxDataDetail[$item['custom_sku_id']][$v['box_no']])){
                            $boxDataDetail[$item['custom_sku_id']][$v['box_no']] += $item['num'];
                        }else{
                            $boxDataDetail[$item['custom_sku_id']][$v['box_no']] = $item['num'];

                        }
                    }else{
                        $boxDataDetail[$item['custom_sku_id']][$v['box_no']] = $item['num'];
                    }
                }
                // 保存箱号
                if(!in_array($v['box_no'], $boxNos)){
                    $boxNos[] = $v['box_no'];
                }
                $boxAllTotal+=$v['total_num'];
                $boxActualNum += $v['total_actual_num'];
            }
            foreach ($boxDataDetail as &$v){
                foreach ($boxNos as $no){
                    if (!isset($v[$no])){
                        $v[$no] = 0;
                    }
                }
                ksort($v);
                $v = array_values($v);
            }
            // 校验装箱数量是否与下架数量匹配
            if($transfersBoxMdl->onshelf_num!=$boxActualNum){
                throw new \Exception('装箱数据与下架数据不一致！下架数量为：'.$transfersBoxMdl->onshelf_num.'；装箱总数量为：'.$boxAllTotal.'，装箱实际总数量为：'.$boxActualNum);
            }
            // 校验装箱数量是否与补货计划匹配
            $requestDetailMdl = db::table('amazon_buhuo_detail')->where('request_id', $params['request_id'])->get();
            $error = '';
            foreach ($requestDetailMdl as $item){
                if (array_key_exists($item->custom_sku_id, $boxDataDetail)){
                    $totalNum = array_sum($boxDataDetail[$item->custom_sku_id]);
                    if ($totalNum != $item->request_num){
                        $error .= '库存sku：'.$item->custom_sku.'装箱数量与计划补货数量不匹配，补货请求数量为：'.$item->request_num.'，装箱数量为：'.$totalNum;
                        continue;
                    }
                    $id = db::table('amazon_buhuo_detail')->where('id', $item->id)->update(['box_data_detail' => json_encode($boxDataDetail[$item->custom_sku_id])]);
                    if (empty($id)){
                        $error .= '库存sku：'.$item->custom_sku.'装箱数据保存失败！';
                    }
                }else{
                    $error .= '库存sku：'.$item->custom_sku.'装箱数据为空！';
                }
            }
            if (!empty($error)){
                throw new \Exception($error);
            }

            // 任务节点自动完成
            if ($requestMdl->request_status < 6) {
                $update_request = Db::table('amazon_buhuo_request')->where('id', $requestMdl->id)->update(['request_status' => 6]);
                if (!$update_request) {
                    throw new \Exception("计划状态修改失败！");
                }
                $return = $call_task->task_son_complete($taskArr);
                if ($return == 1) {
                    if(isset($task2_id)){
                        $taskArr['Id'] = $task2_id;
                        $return2 = $call_task->task_son_complete($taskArr);
                        if(!$return2){
                            throw new \Exception("备货任务自动完成失败！");
                        }
                    }

                } else {
                    throw new \Exception("备货任务自动完成失败！");
                }
            }else{
                throw new \Exception("不可重复装箱！");
            }

            db::commit();
            return ['code' => 200, 'msg' => '保存成功'];
        }catch(\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '保存失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function deleteReplenishmentPackingDetail($params)
    {
        try{
            // 校验装箱码
            if (!isset($params['box_no']) || empty($params['box_no'])){
                throw new \Exception('未给定箱号！');
            }
            if (!isset($params['request_id']) || empty($params['request_id'])){
                throw new \Exception('未给定计划标识！');
            }
            $boxDetailMdl = db::table('amazon_box_data_detail')
                ->where('request_id', $params['request_id'])
                ->where('box_no', $params['box_no'])
                ->get();
            if ($boxDetailMdl->isEmpty()){
                throw new \Exception('未查询到需删除的数据！');
            }else{
                foreach($boxDetailMdl as $v){
                    if ($v->status == 1){
                        throw new \Exception('箱号:'.$v->box_no.'该装箱的数据已汇总，不可删除！');
                    }
                }
            }
            $list = db::table('amazon_box_data_detail')
                ->where('request_id', $params['request_id'])
                ->where('box_no', '>', $params['box_no'])
                ->get();
            db::beginTransaction();
            $delete = db::table('amazon_box_data_detail')
                ->where('request_id', $params['request_id'])
                ->where('box_no', $params['box_no'])
                ->delete();
            if (empty($delete)){
                throw new \Exception('删除数据数量：'.$delete);
            }
            $error = '';
            foreach ($list as $v){
                $boxNo = $v->box_no - 1;
                $update = db::table('amazon_box_data_detail')
                    ->where('id', $v->id)
                    ->update(['box_no' => $boxNo]);
                if (empty($update)){
                    $error .= '第'.$v->box_no.'箱箱号更新失败！';
                }
            }
            if (!empty($error)){
                throw new \Exception($error);
            }

            db::commit();
            return ['code' => 200, 'msg' => '删除成功！箱号为:'.$params['box_no']];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '删除失败！原因:'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function buhuoRequestFbaShippment($params)
    {
        try{
            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    if($users){
                        $params['user_id'] = $users->Id;
                    }else{
                        throw new \Exception('未给定操作人标识！');
                    }
                }else{
                    throw new \Exception('未给定操作人标识！');
                }
            }
            if (!isset($params['request_ids']) || empty($params['request_ids'] || !is_array($params['request_ids']))){
                throw new \Exception('未给定补货计划标识或给定标识格式不正确！');
            }
            $buhuoRequestMdl = db::table('amazon_buhuo_request')
                ->whereIn('id', $params['request_ids'])
                ->get()
                ->keyBy('id');
            $error = '';
            $shopId = [];
            $warehouseId = [];
            foreach ($params['request_ids'] as $id){
                $buhuoRequest = $buhuoRequestMdl[$id] ?? [];
                if (empty($buhuoRequest)){
                    $error .= '计划ID：'.$id.'补货请求不存在！'."\n";
                    continue;
                }
                if (!in_array($buhuoRequest->shop_id, $shopId)){
                    $shopId[] = $buhuoRequest->shop_id;
                }
                if (count($shopId) > 1){
                    $error .= '计划ID：'.$id.'店铺不一致不可合并发货！'."\n";
                    continue;
                }
                if ($buhuoRequest->request_type != 1){
                    $error .= '计划ID：'.$id.'非补货申请类型不可合并发货！'."\n";
                    continue;
                }
//                if (!in_array($buhuoRequest->warehouse, [1, 2])){
//                    $error .= '计划ID：'.$id.'！'."\n";
//                    continue;
//                }
                if (!in_array($buhuoRequest->warehouse, $warehouseId)){
                    $warehouseId[] = $buhuoRequest->warehouse;
                }
                if (count($shopId) > 1){
                    $error .= '计划ID：'.$id.'发货仓库不一致不可合并发货！'."\n";
                    continue;
                }
                if ($buhuoRequest->fid != 0){
                    $error .= '计划ID：'.$id.'已合并不可再次合并发货！'."\n";
                    continue;
                }
                if ($buhuoRequest->request_status != 4){
                    $error .= '计划ID：'.$id.'状态不为已审核，待备货不可合并发货！'."\n";
                    continue;
                }
                $check = db::table('amazon_buhuo_request')
                    ->where('fid', $id)
                    ->first();
                if (!empty($check)){
                    $error .= '计划ID：'.$id.'已进行过合并发货，不可再次合并发货！'."\n";
                    continue;
                }
                if ($buhuoRequest->is_publish_fba != 0){
                    $error .= '计划ID：'.$id.'补货请求不可重复发货！'."\n";
                    continue;
                }
            }
            if (!empty($error)){
                throw new \Exception($error);
            }
            db::begintransaction();

            $buhuoRequest = $buhuoRequestMdl[$params['request_ids'][0]];
            $warehouseId = $buhuoRequest->warehouse;
            $shopId = $buhuoRequest->shop_id;
            $shopMdl = db::table('shop')
                ->where('Id', $shopId)
                ->first();
            $platformId = $shopMdl->platform_id;
            $msg = '';
            if (count($params['request_ids']) > 1){
                // 合并补货计划
                foreach ($params['request_ids'] as $resId){
                    $update = db::table('goods_transfers')
                        ->where('order_no', $resId)
                        ->update(['is_push' => -1]);
                    if (!empty($update)){
                        $msg .= '计划Id：'. $resId .'取消fba出库单更新推送状态失败！';
                    }
                    $update = db::table('goods_transfers_box')
                        ->where('order_no', $resId)
                        ->update(['is_delete' => 1]);
                    if (!empty($update)){
                        $msg .= '计划Id：'. $resId .'删除中转箱失败！';
                    }
                }

                $detailMdl = db::table('amazon_buhuo_detail')
                    ->whereIn('request_id', $params['request_ids'])
                    ->get();
                $detailList = [];
                foreach ($detailMdl as $d){
                    if (isset($detailList[$d->custom_sku_id])){
                        $detailList[$d->custom_sku_id]->request_num += $d->request_num;
                    }else{
                        $detailList[$d->custom_sku_id] = $d;
                    }
                }
                if(!isset($params['transportation_id'])){
                    throw new \Exception('请选择运输方式！');
                }
                $transportationMdl = db::table('transportation_mode')
                    ->where('id', $params['transportation_id'])
                    ->first();
                if (empty($transportationMdl)){
                    throw new \Exception('运输方式不存在！');
                }
                $transportation_date = date("Y-m-d", strtotime("+{$transportationMdl->expected_duration} day"));

                $requestId = DB::table('amazon_buhuo_request')
                    ->insertGetId([
                        'shop_id' => $buhuoRequest->shop_id,
                        'request_userid' => $params['user_id'],
                        'warehouse'=> $buhuoRequest->warehouse,
                        'request_status' => 4,
                        'delivery_date' => date('Y-m-d H:i:s', microtime(true)),
                        'request_time' => date('Y-m-d H:i:s', microtime(true)),
                        'request_type' => 1,
                        'transportation_date' => $transportation_date,
                        'tag' => $params['tag'],
                        'transportation_mode_name' => $transportationMdl->name,
                        'is_publish_fba' => 1,
                    ]);
                if (empty($requestId)){
                    throw new \Exception('补货计划合并失败！');
                }

                $request_link = '/amazon_buhuo_data?id=' . $requestId;

                $update = DB::table('amazon_buhuo_request')
                    ->where('id', $requestId)
                    ->update([
                        'request_link' => $request_link
                    ]);

                $update = DB::table('amazon_buhuo_request')
                    ->whereIn('id', $params['request_ids'])
                    ->update([
                        'fid' => $requestId,
                        'is_publish_fba' => 1
                    ]);
                $msg = '本次合并生成新的计划Id：'.$requestId;
                foreach ($detailList as $d){
                    $save = [
                        'request_id' => $requestId,
                        'sku' => $d->sku,
                        'custom_sku' => $d->custom_sku,
                        'create_time' => date('Y-m-d H:i:s', microtime(true)),
                        'shop_id' => $d->shop_id,
                        'category_id' => $d->category_id,
                        'spu' => $d->spu,
                        'user_id' => $d->user_id,
                        'spu_id' => $d->spu_id,
                        'sku_id' => $d->sku_id,
                        'custom_sku_id' => $d->custom_sku_id,
                        'request_num' => $d->request_num,
                        'transportation_mode_name' => $transportationMdl->name,
                        'transportation_type' => $transportationMdl->type,
                    ];

                    $detailId = db::table('amazon_buhuo_detail')
                        ->insertGetId($save);
                    if (empty($detailId)){
                        throw new \Exception('补货计划详情新增失败！');
                    }
                }

                $box_code = $this->Addbox($requestId, $warehouseId);//新增任务中转箱

                $request_total_num = 0;
                if (empty($detailList)){
                    throw new \Exception('补货计划详情为空！');
                }
                foreach ($detailList as $d){
                    $request_total_num += $d->request_num;

                    if($warehouseId == 1 || $warehouseId == 2){
                        if($box_code){
                            $res = $this->PointsLocation($d->custom_sku_id, $warehouseId, $d->request_num, $box_code, $d->custom_sku, $platformId,6,1);
                            if($res!=1){
                                throw new \Exception($res);
                            }
                        }else{
                            throw new \Exception('新增出库任务失败！');
                        }
                    }

                    $insert_goods_detail = DB::table('goods_transfers_detail')->insert([
                        'order_no'=> $requestId,
                        'spu'=>$d->spu,
                        'custom_sku'=>$d->custom_sku,
                        'transfers_num'=>$d->request_num,
                        'createtime'=> date('Y-m-d H:i:s', microtime(true)),
                        'spu_id'=>$d->spu_id,
                        'custom_sku_id'=>$d->custom_sku_id
                    ]);
                    if(!$insert_goods_detail){
                        throw new \Exception('新增清单明细失败！--'.$d->custom_sku);
                    }
                }
                $insert_goods_transfers = DB::table('goods_transfers')->insert(
                    [
                        'order_no'=>$requestId,
                        'user_id'=>$params['user_id'],
                        'createtime'=>date('Y-m-d H:i:s', microtime(true)),
                        'total_num'=>$request_total_num,
                        'out_house'=>$warehouseId,
                        'in_house'=>20,//亚马逊海外仓
                        'is_push'=>2,
                        'type'=>2,
                        'type_detail'=>6,
                        'shop_id'=>$shopId,
                        'platform_id'=>5,
                    ]);
                if(!$insert_goods_transfers){
                    throw new \Exception('新增清单失败!');
                }
            }else if (count($params['request_ids']) == 1){
//                // 不合并
                $requestId = $params['request_ids'][0];
                db::table('amazon_buhuo_request')
                    ->where('id', $requestId)
                    ->update([
                        'is_publish_fba' => 1
                    ]);
                $taskMdl = db::table('tasks')
                    ->where('class_id', 127)
                    ->where('ext', 'like', '%'.$requestId.'%')
                    ->where('is_deleted', 0)
                    ->first();
                if (empty($taskMdl)){
                    throw new \Exception('未查询到计划Id：'.$requestId.'补货申请审核任务！');
                }
                $ext = json_decode($taskMdl->ext, true);
                if (!isset($ext['start_time'])){
                    throw new \Exception('计划Id：'.$requestId.'补货申请审核任务未绑定销售开始时间！');
                }
                if (!isset($ext['end_time'])){
                    throw new \Exception('计划Id：'.$requestId.'补货申请审核任务未绑定销售结束时间！');
                }
                $params['start_time'] = $ext['start_time'];
                $params['end_time'] = $ext['end_time'];

                $goodsTransferMdl = db::table('goods_transfers')
                    ->where('order_no', $requestId)
                    ->where('is_push', 2)
                    ->first();
                if (empty($goodsTransferMdl)) {
                    throw new \Exception('计划Id：' . $requestId . '未查询到fba出库单记录！');
                }
                $boxMdl = db::table('goods_transfers_box')
                    ->where('order_no', $requestId)
                    ->where('is_delete', 0)
                    ->first();
                if (empty($boxMdl)){
                    throw new \Exception('计划Id：'.$requestId.'未查询到中转箱数据！');
//                    $box_code = $this->Addbox($requestId, $warehouseId);//新增任务中转箱
//                    $detailList = db::table('amazon_buhuo_detail')
//                        ->where('request_id', $params['request_ids'][0])
//                        ->get();
//                    $request_total_num = 0;
//                    if (empty($detailList)){
//                        throw new \Exception('补货计划详情为空！');
//                    }
//                    foreach ($detailList as $d){
//                        $request_total_num += $d->request_num;
//
//                        if($warehouseId == 1 || $warehouseId == 2){
//                            if($box_code){
//                                $res = $this->PointsLocation($d->custom_sku_id, $warehouseId, $d->request_num, $box_code, $d->custom_sku, $platformId,6,1);
//                                if($res!=1){
//                                    throw new \Exception($res);
//                                }
//                            }else{
//                                throw new \Exception('新增出库任务失败！');
//                            }
//                        }
//
//                        $insert_goods_detail = DB::table('goods_transfers_detail')->insert([
//                            'order_no'=> $requestId,
//                            'spu'=>$d->spu,
//                            'custom_sku'=>$d->custom_sku,
//                            'transfers_num'=>$d->request_num,
//                            'createtime'=> date('Y-m-d H:i:s', microtime(true)),
//                            'spu_id'=>$d->spu_id,
//                            'custom_sku_id'=>$d->custom_sku_id
//                        ]);
//                        if(!$insert_goods_detail){
//                            throw new \Exception('新增清单明细失败！--'.$d->custom_sku);
//                        }
//                    }
//                    $insert_goods_transfers = DB::table('goods_transfers')->insert(
//                        [
//                            'order_no'=>$requestId,
//                            'user_id'=>$params['user_id'],
//                            'createtime'=>date('Y-m-d H:i:s', microtime(true)),
//                            'total_num'=>$request_total_num,
//                            'out_house'=>$warehouseId,
//                            'in_house'=>20,//亚马逊海外仓
//                            'is_push'=>2,
//                            'type'=>2,
//                            'type_detail'=>6,
//                            'shop_id'=>$shopId,
//                            'platform_id'=>5,
//                        ]);
//                    if(!$insert_goods_transfers){
//                        throw new \Exception('新增清单失败!');
//                    }
                }
//                $box_code = $boxMdl->id;

//                foreach ($detailList as $d){
//                    if($warehouseId == 1 || $warehouseId == 2){
//                        if($box_code){
//                            $res = $this->PointsLocation($d->custom_sku_id, $warehouseId, $d->request_num, $box_code, $d->custom_sku, $platformId,6,1);
//                            if($res!=1){
//                                throw new \Exception($res);
//                            }
//                        }else{
//                            throw new \Exception('新增出库任务失败！');
//                        }
//                    }
//                }
            }else{
                throw new \Exception('未给定补货计划标识！');
            }

            $task = new \App\Libs\wrapper\Task();
            $taskId = 0;
            switch ($warehouseId){
                case 1:
                    $addtask = [];
                    $addtask['task_t_id'] = 47;
                    $addtask['user_fz'] = $params['user_id'];
                    $addtask['user_cj'] = $params['user_id'];
                    $addtask['request_id'] = $requestId;
                    $addtask['link'] = '/amazon_buhuo_data?id=' . $requestId;
                    $addtask['start_time'] = $params['start_time'] ?? '';
                    $addtask['end_time'] = $params['end_time'] ?? '';

                    $return['warehouse'] = 1;
                    $taskId = $this->create_fba_shipment_task($addtask);
                    break;
                case 2:
                    $addtask = [];
                    $addtask['task_t_id'] = 440;
                    $addtask['user_fz'] = $params['user_id'];
                    $addtask['user_cj'] = $params['user_id'];
                    $addtask['request_id'] = $requestId;
                    $addtask['link'] = '/amazon_buhuo_data?id=' . $requestId;
                    $addtask['start_time'] = $params['start_time'] ?? '';
                    $addtask['end_time'] = $params['end_time'] ?? '';

                    $return['warehouse'] = 1;
                    $taskId = $this->create_fba_shipment_task($addtask);
                    break;
                case 3:
                    $addtask = [];
                    $addtask['task_t_id'] = 885;
                    $addtask['user_fz'] = $params['user_id'];
                    $addtask['user_cj'] = $params['user_id'];
                    $addtask['request_id'] = $requestId;
                    $addtask['link'] = '/amazon_buhuo_data?id=' . $requestId;
                    $addtask['start_time'] = $params['start_time'] ?? '';
                    $addtask['end_time'] = $params['end_time'] ?? '';

                    $return['warehouse'] = 1;
                    $taskId = $this->create_fba_shipment_task($addtask);
                    break;
                default:
                    throw new \Exception('未定义的发货仓库 ---- '.$warehouseId);
                    break;
            }
            if (empty($taskId)){
                throw new \Exception('fba出库任务生成失败！');
            }
            $result = $task->tasks_examine(['task_id' => $taskId, 'token' => $params['token'], 'state' => 3]);
            if ($result != 1){
                throw new \Exception('fba出库任务审核失败！'.$result);
            }
            db::commit();
            return ['code' => 200, 'msg' => '发布成功！'.$msg];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '发布失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function updateBuhuoDetailRequestNum($params)
    {
        try {
            if (!isset($params['user_id']) || empty($params['user_id'])) {
                if (isset($params['token']) && !empty($params['token'])) {
                    $users = db::table('users')->where('token', $params['token'])->first();
                    if ($users) {
                        $params['user_id'] = $users->Id;
                    } else {
                        throw new \Exception('未给定创建人标识！');
                    }
                } else {
                    throw new \Exception('未给定创建人标识！');
                }
            }
            if (!isset($params['request_id'])){
                throw new \Exception('未给定补货计划标识！');
            }

            $buhuoRequestMdl = db::table('amazon_buhuo_request')
                ->where('id', $params['request_id'])
                ->first();
            if (empty($buhuoRequestMdl)){
                throw new \Exception('补货计划不存在！');
            }
            $lock = Redis::get('update_buhuo_request:'.$buhuoRequestMdl->id);
            if($lock){
                throw new \Exception("操作繁忙！请等待60秒后再次操作！");
            }
            Redis::setex('update_buhuo_request:'.$buhuoRequestMdl->id, 61, 1);
            if ($buhuoRequestMdl->request_status != 3){
                throw new \Exception('补货计划状态非已发布，待审核不可修改！');
            }
            if ($buhuoRequestMdl->request_type != 1){
                throw new \Exception('非补货类型不可修改！');
            }
            if ($buhuoRequestMdl->is_publish_fba != 0){
                throw new \Exception('已发布fba任务不可修改！');
            }
            if ($buhuoRequestMdl->fid != 0){
                throw new \Exception('已合并补货的计划不可修改！');
            }
            if (!in_array($buhuoRequestMdl->warehouse, [1, 2])){
                throw new \Exception('补货计划发货仓库非同安仓/泉州仓不可修改！');
            }
            $taskMdl = db::table('tasks')
                ->where('is_deleted', 0)
                ->where('state', 1)
                ->where('class_id', 127)
                ->where('ext', 'like', '%'.$buhuoRequestMdl->id.'%')
                ->first();
            if (empty($taskMdl)){
                throw new \Exception('未查询到该补货计划的待审核补货申请任务！');
            }
            if (!isset($params['sku_data'])){
                throw new \Exception('未给定修改详情！');
            }
            db::beginTransaction();
            $goodTransferMdl = db::table('goods_transfers')
                ->where('order_no', $buhuoRequestMdl->id)
                ->where('is_push', 2)
                ->where('type_detail', 6)
                ->first();
            if (empty($goodTransferMdl)){
                throw new \Exception('未查询到fba出库单信息！');
            }
            $delete = db::table('goods_transfers_detail')
                ->where('order_no', $buhuoRequestMdl->id)
                ->delete();
            $goodTransferBoxMdl = db::table('goods_transfers_box')
                ->where('order_no', $buhuoRequestMdl->id)
                ->where('is_delete', 0)
                ->first();
            if (empty($goodTransferBoxMdl)){
                throw new \Exception('未查询到中转箱信息！');
            }
            $update = db::table('goods_transfers_box')
                ->where('id', $goodTransferBoxMdl->id)
                ->update([
                    'box_num' => 0
                ]);
            $delete = db::table('goods_transfers_box_detail')
                ->where('box_id', $goodTransferBoxMdl->id)
                ->delete();
            foreach ($params['sku_data'] as $d){
                $deailMdl = db::table('amazon_buhuo_detail')
                    ->where('request_id', $buhuoRequestMdl->id)
                    ->where('custom_sku_id', $d['custom_sku_id'])
                    ->update([
                        'request_num' => $d['request_num']
                    ]);
            }
            $buhuoDetailMdl = db::table('amazon_buhuo_detail as a')
                ->where('request_id', $buhuoRequestMdl->id)
                ->get();

            $shopMdl = db::table('shop')
                ->where('Id', $buhuoRequestMdl->shop_id)
                ->first();
            if (empty($shopMdl->platform_id)){
                throw new \Exception('未查询到平台信息！');
            }
            $total_num = 0;
            foreach($buhuoDetailMdl as $v){
                $total_num += $v->request_num;
                $res = $this->PointsLocation($v->custom_sku_id, $buhuoRequestMdl->warehouse, $v->request_num, $goodTransferBoxMdl->id, $v->custom_sku, $shopMdl->platform_id, 6, 1);
                if($res!=1){
                    throw new \Exception($res);
                }
                $insert_goods_detail = DB::table('goods_transfers_detail')->insert([
                    'order_no'=> $v->request_id,
                    'spu'=>$v->spu,
                    'custom_sku'=>$v->custom_sku,
                    'transfers_num'=>$v->request_num,
                    'createtime'=> date('Y-m-d H:i:s', microtime(true)),
                    'spu_id'=>$v->spu_id,
                    'custom_sku_id'=>$v->custom_sku_id
                ]);
                if(!$insert_goods_detail){
                    throw new \Exception('新增清单明细失败！--'.$v->custom_sku);
                }
            }
            db::table('goods_transfers')
                ->where('order_no', $buhuoRequestMdl->id)
                ->where('is_push', 2)
                ->where('type_detail', 6)
                ->update([
                    'total_num' => $total_num
                ]);
            db::commit();
            return ['code' => 200, 'msg' => '修改成功！'];
        }catch (\Exception $e){
            db::rollback();

            return ['code' => 500, 'msg' => '修改失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
    }

    public function getInventoryReportList($params)
    {
        $list = db::table('custom_sku_inventory_month as a')
            ->leftJoin('self_custom_sku as b', 'a.custom_sku_id', '=', 'b.id')
            ->leftJoin('self_spu as c', 'a.spu_id', '=', 'c.id');

        if (isset($params['year'])){
            $list = $list->where('a.year', $params['year']);
        }

        if (isset($params['month']) && isset($params['year'])){
            $list = $list->where('a.month', $params['month']);
        }

        if (isset($params['custom_sku'])){
            $list = $list->where('b.custom_sku', 'like', '%'.$params['custom_sku'].'%')
                ->orwhere('b.old_custom_sku', 'like', '%'.$params['custom_sku'].'%');
        }

        if (isset($params['spu'])){
            $list = $list->where('c.spu', 'like', '%'.$params['spu'].'%')
                ->orwhere('c.old_spu', 'like', '%'.$params['spu'].'%');
        }

        if (isset($params['user_id'])){
            $list = $list->where('a.user_id', $params['user_id']);
        }

        if (isset($params['warehouse_id'])){
            $list = $list->where('a.warehouse_id', $params['warehouse_id']);
        }

        if (isset($params['platform_id'])){
            $list = $list->where('a.platform_id', $params['platform_id']);
        }

        $count = $list->count();

        if ((isset($params['limit']) || isset($params['page'])) && (!isset($params['post_type']) || $params['post_type'] != 2)){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offset = $limit * ($page-1);
            $list = $list->limit($limit)->offset($offset);
        }

        $list = $list->get(['a.*', 'b.old_custom_sku','b.name', 'b.custom_sku', 'c.spu', 'c.old_spu']);

        $platformMdl = db::table('platform')
            ->get(['Id', 'name'])
            ->pluck('name', 'Id');
        $warehouseMdl = db::table('cloudhouse_warehouse')
            ->get(['id', 'warehouse_name'])
            ->pluck('warehouse_name', 'id');
        foreach ($list as $v){
            $v->platform_name = $platformMdl[$v->platform_id] ?? '';
            $v->user_name = $this->GetUsers($v->user_id)['account'] ?? '';
            $v->time = $v->year.'-'.$v->month;
            $v->warehouse_name = $warehouseMdl[$v->warehouse_id];
            $v->spu = !empty($v->old_spu) ? $v->old_spu : $v->spu;
        }

        if (isset($params['post_type']) && $params['post_type'] == 2){
            $p['title']='进销存报表导出'.time();
            $title = [
                'warehouse_name'  => '仓库名称',
                'spu'  => '任务名称',
                'custom_sku' => '库存sku',
                'name'            => '产品名称',
                'platform_name'            => '平台',
                'user_name'       => '负责人',
                'num_first'       => '期初库存数量',
                'price_first'    => '期初库存金额',
                'num_type_detail_2'      => '采购入库数量',
                'price_type_detail_2'      => '采购入库金额',
                'num_type_detail_3'      => '手工入库数量',
                'price_type_detail_3'      => '手工入库金额',
                'num_type_detail_4'      => '样品退回入库数量',
                'price_type_detail_4'      => '样品退回入库金额',
                'num_type_detail_5'      => '订单退货入库数量',
                'price_type_detail_5'      => '订单退货入库金额',
                'num_type_detail_18'      => '组货入库数量',
                'price_type_detail_18'      => '组货入库金额',
                'num_type_detail_1'      => '仓库调拨入库数量',
                'price_type_detail_1'      => '仓库调拨入库金额',
                'num_type_detail_12'      => '订单出库数量',
                'price_type_detail_12'      => '订单出库金额',
                'num_type_detail_9'      => '采购退回出库数量',
                'price_type_detail_9'      => '采购退回出库金额',
                'num_type_detail_17'      => '组货出库数量',
                'price_type_detail_17'      => '组货出库金额',
                'num_type_detail_11'      => '手工出库数量',
                'price_type_detail_11'      => '手工出库金额',
                'num_type_detail_10'      => '样品调拨出库数量',
                'price_type_detail_10'      => '样品调拨出库金额',
                'num_type_detail_8'      => '第三方仓出库数量',
                'price_type_detail_8'      => '第三方仓出库金额',
                'num_type_detail_6'      => 'fba出库数量',
                'price_type_detail_6'      => 'fba出库金额',
                'num_type_detail_7'      => '仓库调拨出库数量',
                'price_type_detail_7'      => '仓库调拨出库金额',
                'num_end'       => '期末库存数量',
                'price_end'    => '期末库存金额',
            ];

            $p['title_list']  = $title;
            $p['data'] =  $list;
            $userId = 1;
            if (!isset($params['user_id']) || empty($params['user_id'])){
                if (isset($params['token']) && !empty($params['token'])){
                    $users = db::table('users')->where('token',$params['token'])->first();
                    if($users){
                        $userId = $users->Id;
                    }else{
                        $userId = 0;
                    }
                }
            }
            $find_user_id = $userId;
            $p['user_id'] = $find_user_id;
            $p['type'] = '进销存报表导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
                return ['code' => 200, 'msg' => '加入队列成功！'];
            } catch(\Exception $e){
                return ['code' => 500, 'msg' => '加入队列失败！'.$e->getMessage()];
            }
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $list]];
    }
}
